• 欢迎光临~

WPF Canvas image高分辨率打印

开发技术 开发技术 2022-07-27 次浏览

与其将Viewport3DVisual传递给PrintVisual方法, 不如先创建一个300 DPI 的RenderTargetBitmap并调用Render方法以在位图上渲染Viewport3DVisual然后将位图放入Image元素中,通过调用MeasureArrange对其进行布局传递,并将Image元素传递给PrintVisual方法。

 void NormalPrintOnClick(object sender, RoutedEventArgs args)
        {
            PrintDialog dlg = new PrintDialog();

            if (dlg.ShowDialog().GetValueOrDefault())
            {
                dlg.PrintVisual(visual3d, "PrintViewport3DVisual: 3D Cube");
            }
        }

        void HiResPrintOnClick(object sender, RoutedEventArgs args)
        {
            PrintDialog dlg = new PrintDialog();

            if (dlg.ShowDialog().GetValueOrDefault())
            {
                Rect rect = visual3d.Viewport;

                // Scale dimensions from 96 dpi to 600 dpi.
                double scale = 600 / 96;

                RenderTargetBitmap bitmap = new RenderTargetBitmap((int) (scale * (rect.Width + 1)), 
                                                                   (int) (scale * (rect.Height + 1)), 
                                                                   scale * 96, 
                                                                   scale * 96, PixelFormats.Default);
                bitmap.Render(visual3d);

                // Create Image element for hosting bitmap.
                Image img = new Image();
                img.Source = bitmap;
                img.Stretch = Stretch.None;

                // Submit Image element to layout pass so it gets finite size.
                img.Measure(new Size(dlg.PrintableAreaWidth, 
                                     dlg.PrintableAreaHeight));
                Size sizeImage = img.DesiredSize;
                img.Arrange(new Rect(new Point(0, 0), sizeImage));

                // Print the Image element.
                dlg.PrintVisual(img, "PrintViewport3DVisual: 3D Cube");
            }
        }

  

public void ExportToPng(Uri path, Image surface)
{
if (path == null) return;

Transform transform = surface.LayoutTransform;
surface.LayoutTransform = null;

System.Windows.Size size = new System.Windows.Size(surface.Width, surface.Height);
surface.Measure(size);
surface.Arrange(new Rect(size));

RenderTargetBitmap renderBitmap =
new RenderTargetBitmap(
(int)size.Width,
(int)size.Height,
96d,
96d,
PixelFormats.Pbgra32);
renderBitmap.Render(surface);

using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(outStream);
}
surface.LayoutTransform = transform;
}

  

程序员灯塔
转载请注明原文链接:WPF Canvas image高分辨率打印
喜欢 (0)