使用viewbox将XAML保存到png?

时间:2012-02-21 22:11:45

标签: c# xaml

我有一个带有多行文本框的简单表单。

然后我有这个代码:

using (Stream stream = new MemoryStream())
{
    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
    {
        writer.WriteLine(textBox1.Text);
        writer.Flush();
        stream.Position = 0;
        FrameworkElement element = XamlReader.Load(stream) as FrameworkElement;


        Size renderingSize = new Size(128, 128);
        element.Measure(renderingSize);
        Rect renderingRectangle = new Rect(renderingSize);
        element.Arrange(renderingRectangle);
        element.UpdateLayout();

        Rect bounds = VisualTreeHelper.GetDescendantBounds(element);
        RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)element.ActualWidth,
            (int)element.ActualHeight,
            96, 96, PixelFormats.Pbgra32);

        DrawingVisual visual = new DrawingVisual();
        using (DrawingContext context = visual.RenderOpen())
        {
            VisualBrush brush = new VisualBrush(element);
            context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
        }
        renderBitmap.Render(visual);
        try
        {
            PngBitmapEncoder enc = new PngBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(renderBitmap));
            using (Stream outputStream = File.OpenWrite(@"T:\test.png"))
            {
                enc.Save(outputStream);
            }
        }
        catch (ObjectDisposedException)
        {
            // IF the operation lasted too long, the object might be disposed already
        }
    }
}

我的textbox1的内容如下

<?xml version="1.0" encoding="utf-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Canvas Width="48" Height="48" Clip="F1 M 0,0L 48,0L 48,48L 0,48L 0,0">
    <Path Width="24" Height="24" Canvas.Left="12" Canvas.Top="12" Stretch="Fill" Fill="#FF000000" Data="F1 M 22,12L 26,12L 26,22L 36,22L 36,26L 26,26L 26,36L 22,36L 22,26L 12,26L 12,22L 22,22L 22,12 Z "/>
  </Canvas>
</Viewbox>

如果我运行此代码,视图框没有任何效果,但如果我采用这个xaml代码并将代码粘贴到表达式混合(删除xml标题)然后我得到我想要的结果(内容填充整个屏幕)。

那么为什么视图框在我的代码中不起作用,我缺少什么?

0 个答案:

没有答案