【发布时间】:2023-08-19 01:54:01
【问题描述】:
我希望能够加载路径的 WPF 资源字典并将它们一一输出到文件(jpg,bmp,没关系)。这将位于一个类库中,MVC 应用程序将访问该类库以呈现到 http 流,因此我纯粹在代码中执行此操作(没有 XAML 页面)。
我已经能够加载字典并遍历路径,但是当我将图像保存到磁盘时,它们是空白的。我知道我遗漏了一些琐碎的事情,例如将路径应用于几何图形,或者将其添加到包含矩形或其他内容中,但我的 WPF 经验有些有限。
我正在使用以下代码:
我有一个 WPF 资源字典,其中包含多个路径,如下所示:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Path x:Key="Path1" Data="M 100,200 C 100,25 400,350 400,175 H 280" Fill="White" Margin="10,10,10,10" Stretch="Fill"/>
<Path x:Key="Path2" Data="M 10,50 L 200,70" Fill="White" Margin="10,10,10,10" Stretch="Fill"/>
</ResourceDictionary>
以及读取和输出文件的类:
public class XamlRenderer
{
public void RenderToDisk()
{
ResourceDictionary resource = null;
Thread t = new Thread(delegate()
{
var s = new FileStream(@"C:\Temp\myfile.xaml", FileMode.Open);
resource = (ResourceDictionary)XamlReader.Load(s);
s.Close();
foreach (var item in resource)
{
var resourceItem = (DictionaryEntry)item;
var path = (System.Windows.Shapes.Path)resourceItem.Value;
var panel = new StackPanel();
var greenBrush = new SolidColorBrush {Color = Colors.Green};
path.Stroke = Brushes.Blue;
path.StrokeThickness = 2;
path.Fill = greenBrush;
panel.Children.Add(path);
panel.UpdateLayout();
string filepath = @"C:\Temp\Images\" + resourceItem.Key + ".jpg";
SaveImage(panel, 64, 64, filepath);
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void SaveImage(Visual visual, int width, int height, string filePath)
{
var bitmap =
new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(visual);
var image = new PngBitmapEncoder();
image.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream fs = File.Create(filePath))
{
image.Save(fs);
}
}
}
【问题讨论】:
标签: wpf path bitmap render resourcedictionary