1

Using this method, I want to render a canvas to a bitmap.

When I add a Shape to the Canvas, it is rendered twice the specified size.

In the example below, I am drawing a line from (0;0) to (50;50) on a canvas of size 200 by 200.

    public bool exportToBmp(string path, int dpi = 96)
    {
        if (path == null)
            return false;

        var canvas = new System.Windows.Controls.Canvas();

        // This diagonal Line should span a quarter of the rendered Image
        var myLine = new System.Windows.Shapes.Line();
        myLine.Stroke = System.Windows.Media.Brushes.LightSteelBlue;
        myLine.X1 = 0;
        myLine.X2 = 50;
        myLine.Y1 = 0;
        myLine.Y2 = 50;
        myLine.StrokeThickness = 2;
        canvas.Children.Add(myLine);

        canvas.Height = 200;
        canvas.Width = 200;
        Size size = new Size(canvas.Width, canvas.Height);

        canvas.Measure(size);
        canvas.Arrange(new Rect(size));

        var width = (int)canvas.ActualWidth;
        var height = (int)canvas.ActualHeight;

        RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Pbgra32);
        bmp.Render(canvas);

        PngBitmapEncoder image = new PngBitmapEncoder();
        image.Frames.Add(BitmapFrame.Create(bmp));
        using (Stream fs = File.Create(path))
        {
            image.Save(fs);
        }

        return false;
    }

The rendered image I get is 200 by 200 px big, but the diagonal goes all the way to (100;100)

output Bitmap

What am I doing wrong?

Community
  • 1
  • 1
Philipp
  • 499
  • 5
  • 17

1 Answers1

2

When I run your code, I see the following image (border added for clarity):

enter image description here

Are you passing a DPI other than 96?

What DPI settings are in use on your computer?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742