我是 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);
}
}