将 XAML 文件转换为 BitmapImage [英] Convert an XAML file to a BitmapImage

查看:31
本文介绍了将 XAML 文件转换为 BitmapImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 XAML(文本)文件创建一个具有所需分辨率的 BitmapImage.我该怎么做?

I want to create a BitmapImage with a desired resolution from an XAML (text) file. how can I do that?

谢谢.

推荐答案

加载 Xaml 文件:

To load your Xaml file:

Stream s = File.OpenRead("yourfile.xaml");
Control control = (Control)XamlReader.Load(s);

并创建位图图像:

    public static void SaveImage(Control control, string path)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            GenerateImage(element, stream);
            Image img = Image.FromStream(stream);
            img.Save(path);
        }
    }

    public static void GenerateImage(Control control, Stream result)
    {
        //Set background to white
        control.Background = Brushes.White;

        Size controlSize = RetrieveDesiredSize(control);
        Rect rect = new Rect(0, 0, controlSize.Width, controlSize.Height);

        RenderTargetBitmap rtb = new RenderTargetBitmap((int)controlSize.Width, (int)controlSize.Height, IMAGE_DPI, IMAGE_DPI, PixelFormats.Pbgra32);

        control.Arrange(rect);
        rtb.Render(control);

        PngBitmapEncoder png = new PngBitmapEncoder();
        png.Frames.Add(BitmapFrame.Create(rtb));
        png.Save(result);
    }

    private static Size RetrieveDesiredSize(Control control)
    {
        control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
        return control.DesiredSize;
    }

确保包含正确的库!这些类位于 System.Windows.Media.

Make sure to include the right libraries! The classes are located in System.Windows.Media.

希望这有帮助!

这篇关于将 XAML 文件转换为 BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆