Jonesie
Jonesie

Reputation: 7285

Drawing to a bitmap from a WPF canvas

I have a canvas that contains an Image in which I dislay an existing BMP. I draw rectangles on the canvas and add these to the Children colllection. When I click save, I want to update the underlying BMP file.

The following code works, but the rectangle that gets drawn to the BMP is way smaller than what I drew. I guess there's some difference in the co-ordinates? Maybe I shouldn't be using System.Drawing?

        using (Graphics g = Graphics.FromImage(image))
        {
          g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;

          foreach (var child in canvas.Children)
          {
            if (child is System.Windows.Shapes.Rectangle)
            {
              var oldRect = child as System.Windows.Shapes.Rectangle;

              // need to do something here to make the new rect bigger as the scale is clearly different
              var rect = new Rectangle((int)Canvas.GetLeft(oldRect), (int)Canvas.GetTop(oldRect), (int)oldRect.Width, (int)oldRect.Height);
              g.FillRectangle(Brushes.Black, rect);
            }
          }
          ... code to save bmp   

All suggestions welcome!

Thanks

Upvotes: 1

Views: 3225

Answers (1)

Mark Hall
Mark Hall

Reputation: 54562

Try using the System.Windows.Media.Imaging.RenderTargetBitmap Class (an example here).
Wpf uses Device Independent Graphics so you have to compensate for the DPI :

RenderTargetBitmap bmp = new RenderTargetBitmap((int)Canvas1.Width, (int)Canvas1.Height, 96, 96, PixelFormats.Default);
bmp.Render(Canvas1);

From Third Link:

There are two system factors that determine the size of text and graphics on your screen: resolution and DPI. Resolution describes the number of pixels that appear on the screen. As the resolution gets higher, pixels get smaller, causing graphics and text to appear smaller. A graphic displayed on a monitor set to 1024 x 768 will appear much smaller when the resolution is changed to 1600 x 1200.

Upvotes: 3

Related Questions