繁体   English   中英

RenderTargetBitmap 模糊

[英]RenderTargetBitmap is blurry

嗨,我正在使用 PngBitmapEncoder 从 Canvas 在 memory 中创建图像。

public void CaptureGraphic()
{
    Canvas canvas = new Canvas();
    canvas.SnapsToDevicePixels = true;
    canvas.Height = IMAGEHEIGHT;
    canvas.Width = IMAGEWIDTH;
    Draw(canvas);
    canvas.Arrange(new Rect(0, 0, IMAGEWIDTH, IMAGEHEIGHT));
    member.MemberImage = GetPngFromUIElement(canvas);
}

public static System.Drawing.Image GetPngFromUIElement(Canvas source)
{
    int width = (int)source.ActualWidth;
    int height = (int)source.ActualHeight;

    if (width == 0)
        width = (int)source.Width;
    if (height == 0)
        height = (int)source.Height;


    RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32);
    bitmap.Render(source);

    PngBitmapEncoder enc = new PngBitmapEncoder();
    enc.Interlace = PngInterlaceOption.Off;
    enc.Frames.Add(BitmapFrame.Create(bitmap));

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    enc.Save(ms);

    System.Drawing.Image image = System.Drawing.Image.FromStream(ms);

    ms.Flush();
    ms.Dispose();

    return image;
}

然后我使用 GDI+ DrawImage() 方法将图像发送到打印机。 但是打印的结果是模糊的。

我尝试将原始 canvas 尺寸与打印尺寸相匹配以避免任何缩放,同样我尝试使原始尺寸更大,以便缩放后的图像保持质量,但最终打印的图像总是模糊。

任何人都可以提供任何建议/替代方案。 我已经设置了相当多的 GDI+ 打印例程,现在还不能选择转到 wpf 文档。

谢谢

我得到了同样模糊的结果,并提出了以下代码,它对偏移应用了相同的想法,但是使用了 DrawingVisual 上的 Offset 属性(因为我使用的是 DrawDrawing,它没有与偏移参数):

public static Image ToBitmap(Image source)
{
    var dv = new DrawingVisual();
    // Blur workaround
    dv.Offset = new Vector(0.5, 0.5);
    using (var dc = dv.RenderOpen())
        dc.DrawDrawing(((DrawingImage)source.Source).Drawing);

    var bmp = new RenderTargetBitmap((int)source.Width, (int)source.Height, 96, 96, PixelFormats.Pbgra32);
    bmp.Render(dv);

    var bitMapImage = new Image();
    bitMapImage.Source = bmp;
    bitMapImage.Width = source.Width;
    bitMapImage.Height = source.Height;

    return bitMapImage;
}

您正在以 96 DPI 捕获 bitmap。 不要在 RenderTargetBitmap 的构造函数中使用 96,而是尝试匹配打印机 output 的 DPI。 或者,您可以进行数学运算并计算宽度/高度的差异,并相应地重新调整报告上的图像(结果是报告上的图像会显得更小)。

我有同样的问题。 为了避免模糊的文本和线条,我必须在 X 和 Y 方向上以 0.5 的偏移量绘制所有内容。 例如,一条水平线可以是

drawingContext.DrawLine(pen, new Point(10.5,10.5), new Point(100.5,10.5));

就我而言,我在不同的线程中渲染到 RenderTargetBitmap 以提高 UI 性能。 渲染的 bitmap 然后被冻结并使用

drawingContext.DrawImage(bitmap, new Rect(0.5, 0, bitmap.Width, bitmap.Height));

在这里,我需要一个 0.5 的额外偏移量,但(奇怪的是)只在 X 方向上,这样渲染的图像就不再看起来模糊了。

想我已经找到了答案。

http://www.charlespetzold.com/blog/2007/12/High-Resolution-Printing-of-WPF-3D-Visuals.html

我只需要随着 dpi 和 voila 一起放大图像大小,大大增加了文件大小!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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