【问题标题】:C# WPF Save canvas as image including its child dynamicallyC# WPF 将画布保存为图像,包括其子动态
【发布时间】:2013-01-03 12:39:26
【问题描述】:

我是 wpf 开发的新手。我已经在运行时动态地在画布中添加了一个图像,并且我正在尝试将该图像容器(即画布)保存为 png 图像。但我没有正确获得输出图像。我得到一个空白的png图像。谁能告诉我的代码逻辑有什么问题。

代码

private void CreateSaveBitmap1(string filename, Rect rect)
{
    System.Windows.Controls.Image bg = new System.Windows.Controls.Image();
    bg.Source = new BitmapImage(new Uri(filename, UriKind.Relative));


    Canvas imageCan = new Canvas();
    imageCan.Height = 800;
    imageCan.Width = 1000;

    Canvas.SetLeft(bg, 0);
    Canvas.SetTop(bg, 0);

    bg.RenderTransform = trGrp; //trGrp is the TransformGroup object.


    RenderTargetBitmap rtb = new RenderTargetBitmap((int)imageCan.Width, (int)imageCan.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
    rtb.Render(imageCan);


    //var crop = new CroppedBitmap(rtb, new Int32Rect((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height));            

    BitmapEncoder pngEncoder = new PngBitmapEncoder();
    pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

    using (var fs = System.IO.File.OpenWrite(@"D:\test\nowTest.png"))
    {
        pngEncoder.Save(fs);
    }
}

【问题讨论】:

    标签: c# .net wpf canvas


    【解决方案1】:

    您应该通过调用 UpdateLayoutInvalidateVisual 来强制设置画布的初始布局:

    imageCan.UpdateLayout();
    
    RenderTargetBitmap rtb = ...
    rtb.Render(imageCan);
    

    并且可能需要通过设置BitmapCacheOption.OnLoad 来强制立即加载图像:

    var image = new BitmapImage();
    image.BeginInit();
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(filename, UriKind.Relative);
    image.EndInit();
    bg.Source = image;
    

    【讨论】:

      【解决方案2】:

      我也遇到过类似的问题。
      它不仅会影响 RenderTargetBitmap,还会影响 XPS 和 PDF 输出。 不幸的是,真正对我有用的唯一方法有点丑:
      我必须将其添加到可视化树并调用更新布局。

      意思是我在我的窗口某处有一个画布,添加了它,称为 UpdateLayout,创建了导出并随后将其删除

      其他一切(例如 Clemens 所说的)都行不通。所以这个解决方案非常丑陋,但至少它以某种方式起作用。

      【讨论】:

        【解决方案3】:

        你应该更新画布布局

        使用 UpdateLayout 方法: MyCanvas.UpdateLayout();

        另外,你应该检查画布的高度和风度必须大于0;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-20
          • 2021-06-20
          • 1970-01-01
          • 1970-01-01
          • 2014-03-21
          • 1970-01-01
          相关资源
          最近更新 更多