gpt4 book ai didi

绘图上下文中的 WPF 清除区域?

转载 作者:行者123 更新时间:2023-12-01 12:39:15 25 4
gpt4 key购买 nike

所以我使用 DrawingContext 和 DrawingVisual 生成透明的 PNG。

在 DrawingContext 中,我画了一个矩形。

我现在想在矩形内“切出”一个圆。我该怎么做呢?我没有在绘图上下文中找到任何清除区域的函数。

最佳答案

您可以尝试使用 CombinedGeometry 组合 2 个几何图形(每次)。它具有 GeometryCombineMode 允许您指定一些逻辑组合。在这种情况下,您需要的是 GeometryCombineMode.Xor。矩形和椭圆 (cirlce) 的交点将被切掉。这是演示它的简单代码:

DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
dc.DrawGeometry(Brushes.Blue, null, cb);
}

我希望你知道如何渲染 DrawingVisual。您可以使用一些 RenderTargetBitmap 将其捕获到某种 BitmapSource 中,然后您可以通过多种方式显示此位图。

截图如下:

enter image description here

黑色区域表示颜色是透明的。

如果您想剪切一些复杂的图像(例如绘制的文本或图像)。您可以将 CombinedGeometry 变成某种类型的 OpacityMask(Brush 类型)。我们可以将它变成一个 DrawingBrush,这个画笔可以用作 OpacityMask,可以传递给 DrawingContext.PushOpacityMask 方法:

DrawingVisual dv = new DrawingVisual();                
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
var mask = new DrawingBrush(new GeometryDrawing(Brushes.Blue, null, cb));
dc.PushOpacityMask(mask);
dc.DrawImage(someImage, rect);
dc.DrawText(new FormattedText("Windows Presentation Foundation",
System.Globalization.CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface("Lucida Bright"), 30, Brushes.Red){
MaxTextWidth = rect.Width,
MaxTextHeight = rect.Height,
TextAlignment = TextAlignment.Center
}, new Point());
}

enter image description here

请注意,rect 的大小应为整个绘图的大小。然后定位和其他绘制的东西将完全符合您的要求。

最后,DrawingVisual 还有一个有用的属性,称为 Clip,它是一个 Geometry。因此,您可以准备一些 CombinedGeometry 并将其分配给 DrawingVisual.Clip 属性。

假设您已经有了 DrawingVisual(带有一些绘制的内容,包括文本、图像等)。以下代码将一个洞:

//prepare the geometry, which can be considered as the puncher.
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
//punch the DrawingVisual
yourDrawingVisual.Clip = cb;

关于绘图上下文中的 WPF 清除区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26559401/

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