【问题标题】:Why is my Shapes.Line twice the size I want it to be on Canvas?为什么我的 Shapes.Line 尺寸是我希望它在 Canvas 上的两倍?
【发布时间】:2016-07-21 09:23:18
【问题描述】:

使用this 方法,我想将画布渲染为位图。

当我将Shape 添加到Canvas 时,它会呈现两倍于指定大小。

在下面的示例中,我在大小为 200 x 200 的画布上绘制了一条从 (0;0) 到 (50;50) 的线。

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

我得到的渲染图像是 200 x 200 px 大,但对角线一直到 (100;100)

我做错了什么?

【问题讨论】:

    标签: c# wpf canvas bitmap shapes


    【解决方案1】:

    当我运行您的代码时,我看到以下图像(为清楚起见添加了边框):

    您是否通过了 96 以外的 DPI?

    您的计算机上使用了哪些 DPI 设置?

    【讨论】:

    • 是的,我使用的是 dpi = 200。
    • 它让我走上了正轨。我不知道dpi实际上改变了图像的内容,我以为它只是指定了,100%缩放时图像将呈现在屏幕上的大小
    • 尝试使用 96 的 DPI,而不是 200。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    • 2016-06-24
    • 1970-01-01
    相关资源
    最近更新 更多