【问题标题】:How to convert a ViewBox to an ImageSource?如何将 ViewBox 转换为 ImageSource?
【发布时间】:2010-10-25 13:36:39
【问题描述】:

我正在使用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;
    }
}

}

这就是 Viewbox 声明的样子。 ... 路径> ... 路径> ... 路径> ... 矩形> 网格> 视图框> 视图框>

【问题讨论】:

    标签: wpf viewbox imagesource


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多