开发者

How to draw directly on bitmap (BitmapSource, WriteableBitmap) in WPF?

开发者 https://www.devze.com 2023-04-01 01:45 出处:网络
In GDI+ Winforms I would do: Bitmap b = new Bitmap(32,32); Graphics g = Gr开发者_高级运维aphics.FromImage(b);

In GDI+ Winforms I would do:

Bitmap b = new Bitmap(32,32);
Graphics g = Gr开发者_高级运维aphics.FromImage(b); 
//some graphics code...`

How to do the same thing in WPF, with a DrawingContext?


I see this question was asked in 2011, but I firmly believe that late is better than never, and the only other "answer" nowhere meets this websites criteria for a proper answer, so I will be providing my own to help anyone else that finds this question in the future.

Here is a simple example that shows how to draw a rectangle and saves it to disk. There may be a better (more concise way) of doing this, but alas, every link I've found online results in the same "shrug I don't know" answer.

        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));
        }

As far as I can tell, RenderTargetBitmap is considered an ImageSource, so you should be able to link that to the image source of wpf controls directly without any sort of conversions.


You can use RenderTargetBitmap to render any WPF content into a Bitmap, since it is, itself, a BitmapSource. With this, you can use standard drawing operations in WPF to "draw" on a bitmap.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号