[英]how to render canvas to bitmap excluding out of bounds elements (C# WinRT)
I have a simple paiting app and I'm trying to render a canvas into a bitmap using the RenderTargetBitmap.RenderAsync() method. 我有一个简单的绘画应用程序,我正在尝试使用RenderTargetBitmap.RenderAsync()方法将画布渲染为位图。 If a child element of the canvas exceeds canvas boundaries, the rendered bitmap is bigger than the canvas area... How can I avoid that and get only in-bounds elements rendered?
如果画布的子元素超出了画布边界,则渲染的位图大于画布区域...如何避免这种情况,仅渲染边界元素? I tried the clip property of the canvas but it only works for the UI , not for the rendering.
我尝试了canvas的clip属性,但它仅适用于UI,不适用于渲染。 ClipToBounds is not available in WinRT...
ClipToBounds在WinRT中不可用...
I've ran into same problem. 我遇到了同样的问题。 Here is what worked for me:
这对我有用:
Rect r = new Rect(new Point(0, 0), new Point(canvas.Width, canvas.Height));
foreach (var c in canvas.Children)
c.Clip = new RectangleGeometry() { Rect = r };
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(canvas, (int)canvas.Width, (int)canvas.Height);
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
StorageFile file = await picker.PickSaveFileAsync();
if (file != null)
{
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await
BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)canvas.Width, (uint)canvas.Height,
96, 96, bytes);
await encoder.FlushAsync();
}
}
Basically, you just add Clip to all Canvas's children, so everything what is out of bounds won't be rendered by RenderTargetBitmap. 基本上,您只是将Clip添加到所有Canvas的子级中,所以RenderTargetBitmap不会渲染所有超出范围的东西。
ClipToBounds functionality can be easily added via AttachedProperty: details 可以通过AttachedProperty轻松添加ClipToBounds功能: 详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.