我试图在代码中设置WPF图像的源代码。图像作为资源嵌入到项目中。通过查看示例,我提出了下面的代码。由于某种原因,它不工作-图像不显示。
通过调试,我可以看到流包含图像数据。怎么了?
Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource iconSource = iconDecoder.Frames[0];
_icon.Source = iconSource;
图标的定义如下:<Image x:Name="_icon" Width="16" Height="16" />
还有一种更简单的方法。如果图像在XAML中作为资源加载,并且所讨论的代码是该XAML的幕后代码:
下面是一个XAML文件的资源字典——你唯一关心的一行是ImageBrush,键为“PosterBrush”——其余的代码只是用来显示上下文
<UserControl.Resources>
<ResourceDictionary>
<ImageBrush x:Key="PosterBrush" ImageSource="..\Resources\Images\EmptyPoster.jpg" Stretch="UniformToFill"/>
</ResourceDictionary>
</UserControl.Resources>
在后面的代码中,你可以这样做
ImageBrush posterBrush = (ImageBrush)Resources["PosterBrush"];
将框架放在VisualBrush中:
VisualBrush brush = new VisualBrush { TileMode = TileMode.None };
brush.Visual = frame;
brush.AlignmentX = AlignmentX.Center;
brush.AlignmentY = AlignmentY.Center;
brush.Stretch = Stretch.Uniform;
把VisualBrush放在几何绘图中
GeometryDrawing drawing = new GeometryDrawing();
drawing.Brush = brush;
// Brush this in 1, 1 ratio
RectangleGeometry rect = new RectangleGeometry { Rect = new Rect(0, 0, 1, 1) };
drawing.Geometry = rect;
现在将几何绘图放在DrawingImage中:
new DrawingImage(drawing);
把这个放在你的图片源上,然后是voilà!
你可以做得更简单:
<Image>
<Image.Source>
<BitmapImage UriSource="/yourassembly;component/YourImage.PNG"></BitmapImage>
</Image.Source>
</Image>
在代码中:
BitmapImage image = new BitmapImage { UriSource="/yourassembly;component/YourImage.PNG" };