[英]Convert XAML Window to Bitmap
我有一个简单的XAML像这样:
<UserControl x:Class="blabla.MyView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Name="myUserControl">
<Grid Name="myGrid" Background="White">
<TextBlock Name="myTextBlock"/>
</Grid>
</UserControl>
现在,我想使用此xaml在后台创建一个新视图。 之后,我想更改控件(或自己添加一些控件),将其保存到位图,然后将其分配给剪贴板(仅查看输出)。 我会这样尝试的:
MyView view = new MyView();
view.myTextBlock.Text = "TEST";
Rect bounds = VisualTreeHelper.GetDescendantBounds(view);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush vb = new VisualBrush(view);
ctx.DrawRectangle(vb, null, new Rect(new System.Windows.Point(), bounds.Size));
}
RenderTargetBitmap bmp = new RenderTargetBitmap((int)view.ActualWidth, (int)view.ActualHeight, 96, 96, PixelFormats.Pbgra32);
bmp.Render(dv);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(bmp));
System.Windows.Clipboard.SetImage(pngImage.Frames[0]);
不幸的是, view
的大小没有改变。 尝试通过设置硬编码的宽度/高度来生成黑色图像/位图。
如何使用XAML创建简单的位图?
对官方回答发表评论。 但是,我看到这种解决方案不是最优雅的解决方案。 一般的事情是,窗户,分别。 视图,渲染时会导致黑色区域,而无论如何也无法显示/自身变黑。
工作环境将是显示此视图(如您所写,但在Window中)。 做这个小主意,请将窗口移出可见屏幕,以避免闪烁。 例:
var v = new MainWindow();
v.Top = -10000; // far away
v.Left = -10000; // far away
v.Show();
// .. do rendering
v.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.