在 GDI+ Winforms 中我会这样做:
Bitmap b = new Bitmap(32,32);
Graphics g = Graphics.FromImage(b);
//some graphics code...`
如何在 WPF 中使用 DrawingContext 做同样的事情?
最佳答案
我看到这个问题是在 2011 年提出的,但我坚信迟到总比没有好,唯一的其他“答案”不符合该网站的正确答案标准,因此我将提供自己的答案来帮助任何人else 以后会发现这个问题。
这是一个简单的示例,展示了如何绘制矩形并将其保存到磁盘。可能有更好(更简洁的方法)来执行此操作,但遗憾的是,我在网上找到的每个链接都会得到相同的“耸耸肩,我不知道”的答案。
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 控件的图像源,而无需任何类型的转换。
关于c# - WPF中如何直接在位图(BitmapSource、WriteableBitmap)上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7250282/