简体   繁体   English

将XAML窗口转换为位图

[英]Convert XAML Window to Bitmap

I have a simple XAML like this: 我有一个简单的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>

Now I'd like to create a new view in the background by using this xaml. 现在,我想使用此xaml在后台创建一个新视图。 After this, I'd like to change the controls (or maybe add some controls by myself), save it to a Bitmap and assign it to the Clipboard (just to see the output). 之后,我想更改控件(或自己添加一些控件),将其保存到位图,然后将其分配给剪贴板(仅查看输出)。 I would have tried it like this: 我会这样尝试的:

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]);

Unfortunately, the Size of the view is not being changed. 不幸的是, view的大小没有改变。 Trying to set a hard coded width/height by produces a black image/bitmap. 尝试通过设置硬编码的宽度/高度来生成黑色图像/位图。

How can I create a simple Bitmap out of a XAML? 如何使用XAML创建简单的位图?

Making the comment to official answer. 对官方回答发表评论。 However, I see that this solution is not the most elegant one. 但是,我看到这种解决方案不是最优雅的解决方案。 General thing is, that the window, resp. 一般的事情是,窗户,分别。 view, will result in black area when rendered while it is not visible/redered itself by showing it anyhow. 视图,渲染时会导致黑色区域,而无论如何也无法显示/自身变黑。

The workarround would be to show this view (as you wrote, but in Window). 工作环境将是显示此视图(如您所写,但在Window中)。 Small idea doing this, move the window out of visible screen to avoid flickering. 做这个小主意,请将窗口移出可见屏幕,以避免闪烁。 example: 例:

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM