在 GDI+ Winforms 中我会这样做:
Bitmap b = new Bitmap(32,32);
Graphics g = Graphics.FromImage(b);
//some graphics code...`
如何使用 DrawingContext 在 WPF 中执行相同的操作?
我看到这个问题是在 2011 年提出的,但我坚信迟到总比不到好,唯一的其他“答案”不符合本网站正确答案的标准,所以我将提供自己的答案来帮助其他找到答案的人这个问题在未来。
这是一个简单的示例,展示了如何绘制矩形并将其保存到磁盘。可能有更好(更简洁的方法)来做到这一点,但可惜的是,我在网上找到的每个链接都会产生相同的“耸耸肩,我不知道”答案。
public static void CreateWpfImage()
{
int imageWidth = 100;
int imageHeight = 100;
string outputFile = "C:/Users/Krythic/Desktop/Test.png";
// Create the Rectangle
DrawingVisual visual = new DrawingVisual();
DrawingContext context = visual.RenderOpen();
context.DrawRectangle(Brushes.Red, null, new Rect(20,20,32,32));
context.Close();
// Create the Bitmap and render the rectangle onto it.
RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
bmp.Render(visual);
// Save the image to a location on the disk.
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
encoder.Save(new FileStream(outputFile, FileMode.Create));
}
据我所知, RenderTargetBitmap 被视为 ImageSource,因此您应该能够直接将其链接到 wpf 控件的图像源,而无需进行任何类型的转换。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)