[英]Using a XAML file as a vector Image Source
我希望能夠使用最好在XAML中定義的矢量圖形作為圖像控件的源,就像我現在可以像PNG一樣使用光柵圖像。 這樣我就可以輕松地在位圖和矢量圖像之間進行混合和匹配,如下所示:
<StackPanel>
<Image Source="Images/Namespace.png"/>
<Image Source="Images/Module.xaml"/>
</StackPanel>
Module.xaml很可能將<DrawingImage>
作為其根元素而不是<UserControl>
。
實際上,我真正想要的是這個,所以我的ViewModel可以自行選擇光柵或矢量圖像:
<Image Source="{Binding ImageUri}"/>
這可能嗎? Image.Source可以從給定的URI加載XAML類嗎? 或者只能加載位圖資源?
您可以簡單地將矢量圖形引用為StaticResources:
<Image Source="{StaticResource MyImage}" />
將圖像存儲在ResourceDictionary中作為DrawImage。 Expression Blend可以幫助您生成這些東西:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DrawingImage x:Key="MyImage">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Black" Geometry="M 333.393,... 100.327 Z "/>
<GeometryDrawing Brush="Black" Geometry="F1 M 202.309,... Z "/>
:
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</ResourceDictionary>
1)將DrawingImage.xaml添加到項目中,並將其屬性設置為“BuildAction = Content”和“Copy Always”。 或者你可以從外部動態加載XAML,因為我要解釋的邏輯也適用於loose-xaml。
2)編寫一個轉換器將XAML uri轉換為UIELement,在你的情況下它將始終是DrawingImage
public class FileToUIElementConverter :IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FileStream fileStream = new FileStream((string)parameter, FileMode.Open);
return XamlReader.Load(fileStream) as DrawingImage;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
3)如下編寫XAML
<Window.Resources>
<local:FileToUIElementConverter x:Key="uriToUIElementConverter"/>
</Window.Resources>
<Grid>
<Image Stretch="Fill" Source="{Binding Converter={StaticResource uriToUIElementConverter},ConverterParameter=ImageDrawing.xaml}"/>
</Grid>
使用“資源”類型嵌入XAML資源(DrawingImage)。 它不是一個單獨的文件,可以通過URI直接引用,就像在原始示例中一樣 - 但URI非常重要。 您必須弄清楚Microsoft的“pack”URI語法並使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.