如何将ViewBox转换为ImageSource?

6
我正在使用一个 Viewbox 创建一组图标,我将动态绑定到 WPF 视图。
我将绑定到资源名称,并使用一个 Converter 将资源名称转换为 ImageSource
如果资源是一个 Path,我知道如何做,但如果是 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;
    }
}

这是Viewbox声明的样子。
<Viewbox>
    <Viewbox>
      <Grid>
        <Path>
        ...
        </Path>
        <Path>
        ...
        </Path>
        <Path>
        ...
        </Path>
        <Rectangle>
        ...
        </Rectangle>
      </Grid>
    </Viewbox>
</Viewbox>
1个回答

1
Viewbox是一个视觉元素,因此您需要手动将其渲染为位图。这篇博客文章展示了如何完成此操作,但相关代码如下:
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接