8

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?

0

2 Answers 2

10

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.

8

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.