如何在WPF中直接绘制位图(BitmapSource,WriteableBitmap)?

在GDI + Winforms中我会这样做:

Bitmap b = new Bitmap(32,32); Graphics g = Graphics.FromImage(b); //some graphics code...` 

如何使用DrawingContext在WPF中执行相同的操作?

您可以使用RenderTargetBitmap将任何WPF内容呈现为Bitmap,因为它本身就是BitmapSource 。 这样,您可以在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控件的图像源,而不需要任何类型的转换。