如何将 ViewBox 转换为 ImageSource?
我使用 Viewbox
创建一组图标,并将其动态绑定到 WPF 视图。
我绑定到资源名称并使用 Converter
将资源名称转换为 ImageSource
。
我知道如果资源是 Path
该怎么做,但是如何使用 Viewbox
来做呢?
如果资源是 Path
,这就是我将资源名称转换为 ImageSource
的方法:
public class ResourceNameToImageSourceConverter : BaseValueConverter {
protected override ImageSource Convert(string value, System.Globalization.CultureInfo culture) {
var resource = new ResourceDictionary();
resource.Source = new Uri("pack://application:,,,/MyAssembly;component/MyResourceFolder/ImageResources.xaml", UriKind.Absolute);
var path = resource[value] as Path;
if (path != null) {
var geometry = path.Data;
var geometryDrawing = new GeometryDrawing();
geometryDrawing.Geometry = geometry;
var drawingImage = new DrawingImage(geometryDrawing);
geometryDrawing.Brush = path.Fill;
geometryDrawing.Pen = new Pen();
drawingImage.Freeze();
return drawingImage;
} else {
return null;
}
}
}
And this is what the Viewbox declaration looks like.
<Viewbox>
<Viewbox>
<Grid>
<Path>
...
</Path>
<Path>
...
</Path>
<Path>
...
</Path>
<Rectangle>
...
</Rectangle>
</Grid>
</Viewbox>
</Viewbox>
I'm using a Viewbox
to create a set of icons that I will dynamically bind to a WPF view.
I'm binding to the resource name and using a Converter
to convert the resource name to an ImageSource
.
I know how to do it if the resource is a Path
, but how to do it with a Viewbox
?
This is how I convert the resource name, if the resource is a Path
, to an ImageSource
:
public class ResourceNameToImageSourceConverter : BaseValueConverter {
protected override ImageSource Convert(string value, System.Globalization.CultureInfo culture) {
var resource = new ResourceDictionary();
resource.Source = new Uri("pack://application:,,,/MyAssembly;component/MyResourceFolder/ImageResources.xaml", UriKind.Absolute);
var path = resource[value] as Path;
if (path != null) {
var geometry = path.Data;
var geometryDrawing = new GeometryDrawing();
geometryDrawing.Geometry = geometry;
var drawingImage = new DrawingImage(geometryDrawing);
geometryDrawing.Brush = path.Fill;
geometryDrawing.Pen = new Pen();
drawingImage.Freeze();
return drawingImage;
} else {
return null;
}
}
}
And this is what the Viewbox declaration looks like.
<Viewbox>
<Viewbox>
<Grid>
<Path>
...
</Path>
<Path>
...
</Path>
<Path>
...
</Path>
<Rectangle>
...
</Rectangle>
</Grid>
</Viewbox>
</Viewbox>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Viewbox 是一个视觉元素,因此您需要将其手动“渲染”为位图。这篇博客文章展示了这是如何实现的完成了,但相关代码是:
The Viewbox is a visual element, so you'd need to "render" it manually to a bitmap. This blog post shows how this is done, but the relevant code is: