在运行时生成的图像 [英] Generate Image at Runtime
问题描述
我想呈现在运行时的一些XAML。我的XAML是一个StringBuilder动态构建。作为一个例子,这里是一个示例:
I am trying to render some XAML at runtime. My XAML is dynamically constructed in a StringBuilder. As an example, here is a sample:
StringBuilder xaml = new StringBuilder();
xaml.Append("<Canvas xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" ");
xaml.Append("xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Height=\"135\" ");
xaml.Append("Width=\"210\" Background=\"White\" x:Name=\"Page\">");
string url = "http://www.mydomain.com/images/background.png";
xaml.Append("<Image Width=\"300\" Height=\"200\" Canvas.Left=\"0\" Canvas.Top=\"0\" ");
xaml.Append("x:Name=\"bgImage\" Source=\"");
xaml.Append(url);
xaml.Append("\" />");
xaml.Append("</Canvas>");
请注意此示例中的图像元素。如果我把这个XAML中的.xaml文件运行良好。如果我将其粘贴到混合,它工作正常。但是,我需要等待下载这个形象,则所呈现的XAML转换为.png。为了做到这一点,我使用下面的代码:
Please notice the Image element in this sample. If I put this XAML in a .xaml file it runs fine. If I paste it into Blend, it works fine. However, I need to wait for this image to be downloaded and then convert the rendered XAML to a .png. In order to do this, I am using the following code:
StringReader stringReader = new StringReader(xaml.ToString());
XmlTextReader xmlReader = new XmlTextReader(stringReader);
FrameworkElement frameworkElement = (FrameworkElement)(XamlReader.Load(xmlReader));
Size availableSize = new Size(300, 200);
frameworkElement.Measure(availableSize);
frameworkElement.Arrange(new Rect(availableSize));
BitmapSource bitmap = RenderToBitmap(frameworkElement);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
FileStream fileStream = new FileStream(filename, FileMode.Create);
encoder.Save(fileStream);
fileStream.Close();
的问题是,总是产生巴纽忽略图像元素。我猜测是因为图片来源没有下载。我如何在运行时,包括图像生成一些XAML的图像?
The problem is, the .png that is generated always ignores the Image element. I am guessing because the Image source is not downloaded. How do I generate an image from some XAML at runtime that includes an Image?
感谢您
推荐答案
为什么不直接产生在C#中,而不是创建XAML对象,然后有运行时必须解析呢?做这种方式有以下好处:
Why not just generate the object directly in C# instead of creating XAML and then having the runtime have to parse it? Doing it that way has the following benefits:
- 编译时你的对象的检查你现在的样子这样做,现在可能会引入,因为脂肪指法等运行时错误。
- 更快的对象创建。直接在C#中实例化对象会比快解析器。
- 更易于维护。接下来的程序员一起去,并与此代码的工作将与格式良好的C#主场迎战嵌入的XAML一个更简单的时间。
- Refactorable。您可以重构你的C#代码,以消除重复的代码。
- Compile-time checking of your objects. The way you are doing it now might introduce run-time errors because of a fat-fingering, etc.
- Faster object creation. Instantiating the objects directly in C# will be faster than the parser.
- More maintainable. The next programmer to come along and work with this code will have an easier time with well-formatted C# vs. embedded XAML.
- Refactorable. You can refactor your C# code to eliminate repetitive code.
这篇关于在运行时生成的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!