如何将巨大的Canvas的一部分导出到PNG

时间:2015-04-07 19:17:38

标签: c# wpf

我需要将Canvas导出到多个PNG文件。尝试将整个画布导出到图像,然后裁剪图像失败,因为生成的图像的大小(类似于20.000px x 5.000px)。

现在的策略是将主画布分割成更小的部分,然后将每个部分导出到图像。但是,生成的图像不会显示来自其下方主画布的图像。

有什么想法吗?以下是用于测试画布分割的代码(实际的大于1024x1024):

public void TestPrintPartOfCanvas()
{
    //the main canvas
    var main = new Canvas();
    main.Width = 1024;
    main.Height = 1024;
    main.Background = Brushes.Blue;

    //place something inside the canvas
    var redRect = new System.Windows.Shapes.Rectangle();
    redRect.Fill = Brushes.OrangeRed;
    redRect.Width = 128;
    redRect.Height = 128;

    main.Children.Add(redRect);

    // reset current transform (in case it is scaled or rotated)
    var transform = main.LayoutTransform;
    main.LayoutTransform = null;

    // Get the size of canvas
    var size = new Size(main.Width, main.Height);

    //representing the first part of the main canvas
    var part = new Canvas();
    part.Width = 256;
    part.Height = 256;
    part.Background = Brushes.Transparent;

    main.Children.Add(part);

    // Measure and arrange the surface
    main.Measure(size);
    main.Arrange(new Rect(size));

    // Create a render bitmap and push the part to it
    var renderBitmap = new RenderTargetBitmap((int)part.Width, (int)part.Height, 96d, 96d, PixelFormats.Pbgra32);
    renderBitmap.Render(part);

    // Create a file stream for saving image
    using (var outStream = new FileStream("p:/part.png", FileMode.Create))
    {
        // Use png encoder for our data
        var encoder = new PngBitmapEncoder();
        // push the rendered bitmap to it
        encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
        // save the data to the stream
        encoder.Save(outStream);
    }

    // Restore previously saved layout
    main.LayoutTransform = transform;
}

1 个答案:

答案 0 :(得分:3)

您可以通过调整编配矩形轻松裁剪画布的一部分:

var size = new Size(main.Width, main.Height);
main.Measure(size);

var cropOffset = new Point(-256, -256);
main.Arrange(new Rect(cropOffset, size));

var renderBitmap = new RenderTargetBitmap(256, 256, 96d, 96d, PixelFormats.Pbgra32);
renderBitmap.Render(main);

以上在256,256位置裁剪256x256矩形。