如何将ViewBox转换为ImageSource?

时间:2010-10-25 13:36:40

标签: wpf 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;
    }
}

}

geometryDrawing.Brush = path.Fill; geometryDrawing.Pen = new Pen(); drawingImage.Freeze(); return drawingImage; } else { return null; } }

And this is what the Viewbox declaration looks like.

1 个答案:

答案 0 :(得分:0)

Viewbox是一个可视元素,因此您需要手动将其“渲染”为位图。这篇blog帖子显示了这是如何完成的,但相关的代码是:

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;
}