我的问题与这个非常相似:wpf图像资源以及运行时在wpf控件中更改图像 https://stackoverflow.com/questions/940592/wpf-image-resources-and-changing-image-in-wpf-control-at-runtime#,但有轻微的扭曲。
这是我的 ResourceDictionary.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ImageSource x:Key="DisconnectedIcon">Images/disconnect.png</ImageSource>
<ImageSource x:Key="Synced">Images/tick.png</ImageSource>
<ImageSource x:Key="NotSynced">Images/x.png</ImageSource>
至于后面的 C# 代码,我可以使用以下代码从资源中加载 ImageSource。在其中,我可以看到元数据和图像名称,但无法弄清楚如何将其放入 System.Drawings.Image 中。
var imageSource = (ImageSource)Application.Current.FindResource("Synced");
System.Drawing.Image img = Image.FromFile(???)
我尝试将其转换为 System.Drawing.Image 的原因是将其发送到打印机。
Thanks!
在 WPF 中,每个 UI 元素都扩展了Visual Class http://msdn.microsoft.com/en-us/library/system.windows.media.visual%28v=vs.110%29.aspx which 提供 WPF 中的渲染支持。还有一个RenderTargetBitmap Class http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx有一个Render Method http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.render.aspx这需要一个Visual
对象作为输入参数。所以你可以设置你的ImageSource
as the Source
的财产Image
并简单地渲染Image
to a Bitmap
image:
Image yourImageObject = new Image();
yourImageObject.Source = yourImageSource;
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
renderTargetBitmap.Render(yourImageObject);
// Save to .png file
PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream stream = File.Create(filepath))
{
pngBitmapEncoder.Save(stream);
}
由于这在互联网上已有详细记录,因此我不会在这里重复整个故事。要了解完整的故事,请参阅如何在 WPF 中渲染位图或打印视觉对象 http://www.abhisheksur.com/2010/08/how-to-render-bitmap-or-to-print-visual.htmlDot NET Tricks 网站上的页面,该页面也将帮助您满足打印要求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)