简体   繁体   中英

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

In GDI+ Winforms I would do:

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM