gpt4 book ai didi

wpf - 如何将 ViewBox 转换为 ImageSource?

转载 作者:行者123 更新时间:2023-12-03 14:51:48 27 4
gpt4 key购买 nike

我正在使用 Viewbox创建一组我将动态绑定(bind)到 WPF View 的图标。

我正在绑定(bind)到资源名称并使用 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;
}
}

}
And this is what the Viewbox declaration looks like.



<Viewbox>
<Viewbox>
<Grid>
<Path>
...
</Path>
<Path>
...
</Path>
<Path>
...
</Path>
<Rectangle>
...
</Rectangle>
</Grid>
</Viewbox>
</Viewbox>

最佳答案

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

关于wpf - 如何将 ViewBox 转换为 ImageSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4015089/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com