![](/img/trans.png)
[英]RenderTargetBitmap does not respect ColumnDefinitions width
[英]RenderTargetBitmap does not render included images
我想使用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文件中丢失图像时。
首先,发生的事情是渲染目标,但是ImageControl异步加载BitmapSource,但此时尚未准备好。 如果您等到ImageControl完成加载其源代码,您将获得期望的结果。 有趣的是,ImageControl在完成加载时不会通知您。
因此,简短的答案是:如果您想将现有的和已经加载的视觉效果呈现给图像,只需等待加载嵌套的图像控件即可。
像这样:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
img.LayoutUpdated += img_LayoutUpdated;
}
void img_LayoutUpdated(object sender, EventArgs e)
{
img.LayoutUpdated -= img_LayoutUpdated;
var rt = RenderToBitmap(img);
Save(rt);
}
据我所知,没有简单的方法可以强制ImageControl加载其源代码。 当ImageControl抛出“ Loaded”事件时,并不表示图像已加载。 如果您将ImageControl.Source创建为BitmapImage,则可以执行以下操作:
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelHeight = 100;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri(@"http://www.myurl.com/image.png");
bi.EndInit();
bi.DownloadCompleted += bi_DownloadCompleted; //will be ready to be saved to image when event will fire
img.Source = bi;
或像这样自己下载图像
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData(@"http://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")))
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = stream;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
img.Source = myBitmapImage;
// ready to be saved to image
}
但我认为这不太适合您
如果您的目的是在内存中呈现视觉效果,那么您应该看一下以下问题: 将具有DataBinding的WPF UserControl绘制到图像上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.