[英]How to save Canvas-Control at specific position (in a viewbox) to a png in c# wpf?
I want to develope a .NET application with WPF. 我想用WPF开发一个.NET应用程序。
In the end there should be a Viewbox or something similar, this Viewbox should contain a canvas and in this canvas there could be various things like filled rectangles, ellipses etc. ( like a drawing application eg. paint). 最后,应该有一个Viewbox或类似的东西,该Viewbox应该包含一个画布,并且在该画布中可以有各种东西,例如实心矩形,椭圆等(例如绘图应用程序,例如paint)。
Now I want to implement the functionallity to save the content of the Canvas to a PNG. 现在,我想实现将Canvas的内容保存到PNG的功能。 I tried rendering the Canvas to a RenderTargetBitmap and then saving it.
我尝试将Canvas渲染到RenderTargetBitmap,然后保存它。
The problem here is that I am not able to set specific coordinates, the only thing I can set is the Size (Canvas width & height) of the RenderTargetBitmap, but it will start rendering the Size starting from (0|0) where my Canvas element starts somewhere else. 这里的问题是我无法设置特定的坐标,我唯一可以设置的是RenderTargetBitmap的大小(画布宽度和高度),但是它将开始从(0 | 0)开始渲染我的画布的大小元素从其他地方开始。 Is there some work arround for that??
为此有一些工作吗?
The next Problem is, there should be the posibilty to add pictures as sub-element of the root-Canvas, but how could I care about quality and that everything in the Viewbox is printed? 下一个问题是,应该有可能添加图片作为根Canvas的子元素,但是我如何关心质量以及Viewbox中的所有内容都已打印出来?
Thank you very much! 非常感谢你!
------ EDIT ------ ------编辑------
I think I've got a Solution: 我想我有一个解决方案:
void SaveUsingEncoder(Canvas myCanvas, string fileName)
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)myCanvas.ActualWidth,
(int)myCanvas.ActualHeight,
96,
96,
PixelFormats.Pbgra32);
Rect bounds = VisualTreeHelper.GetDescendantBounds(myCanvas);
Console.WriteLine(bounds.X + "|" + bounds.Y + " " + bounds.Width + "|" + bounds.Height);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(myCanvas);
ctx.DrawRectangle(vb, null, new Rect(bounds.Location, bounds.Size));
}
bitmap.Render(dv);
BitmapFrame frame = BitmapFrame.Create(bitmap);
encoder.Frames.Add(frame);
using (var stream = File.Create(fileName))
{
encoder.Save(stream);
}
}
This saves the complete canvas for me 这为我保存了完整的画布
at specific position - 在特定位置-
I think in your case use Margins. 我认为在您的情况下使用边距。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.