【发布时间】:2015-12-05 14:07:39
【问题描述】:
我想使用 RenderTargetBitmap 功能将 XAML 控件呈现为 PNG 文件。到目前为止效果很好。
但如果 XAML 包含任何图像,则这些图像不会呈现在 PNG 文件中。 这是我的 XAML:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="LayoutRoot"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="336"
d:DesignWidth="336"
Background="DarkGray">
<TextBlock Text="This is my Text"
FontSize="35"
HorizontalAlignment="Center" />
<Image Source="http://www.myurl.com/image.png"
Height="200" /></Grid>
这是我的代码:
private BitmapSource RenderToBitmap(FrameworkElement target)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)target.ActualWidth,
(int)target.ActualHeight,
96, 96, PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(target);
context.DrawRectangle(brush, null, new Rect(new Point(), bounds.Size));
}
renderBitmap.Render(visual);
return renderBitmap;
}
还尝试使用“/Assets/image.png”等引用图像和资源。每次渲染的 PNG 文件中缺少图像时。
【问题讨论】:
-
您检查过您的图片网址吗?
http://www.myurl.com/image.png对我来说是空白的。 -
这只是这个问题的虚拟 URL。它也不适用于正确的图像 URL。
-
尝试在开头调用
target.ApplyTemplate() -
您确定图像在渲染时已加载?