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

8
在 GDI+ Winforms 中,我会这样做:
Bitmap b = new Bitmap(32,32);
Graphics g = Graphics.FromImage(b); 
//some graphics code...`

怎样在WPF中使用DrawingContext做同样的事情?
2个回答

10

我看到这个问题是在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控件的图像源,而不需要任何类型的转换。

8

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接