6

我正在使用 aViewbox创建一组我将动态绑定到 WPF 视图的图标。

我绑定到资源名称并使用 aConverter将资源名称转换为ImageSource.

如果资源是 a Path,我知道该怎么做,但是如何使用 aViewbox呢?

Path如果资源是 a ,这就是我将资源名称转换为 a的方式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>
4

1 回答 1

1

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

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;
}
于 2011-03-04T06:51:05.787 回答