How to convert a ViewBox to an ImageSource?
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 = 开发者_JS百科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>
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:
private static BitmapSource CaptureScreen(Visual target, double dpiX, double dpiY) {
if (target == null)
return null;
Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width * dpiX / 96.0),
(int)(bounds.Height * dpiY / 96.0),
dpiX,
dpiY,
PixelFormats.Pbgra32);
DrawingVisual dv = new DrawingVisual();
using (DrawingContext ctx = dv.RenderOpen()) {
VisualBrush vb = new VisualBrush(target);
ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
}
rtb.Render(dv);
return rtb;
}
精彩评论