具有混合边的多边形

polygon with blended edges

我正在尝试找到在 C# 中绘制边逐渐融入背景颜色的多边形的最佳方法。我正在将多边形绘制到位图,所以目前我正在使用来自 System.Drawing.

的图形 类

多边形将是一个混合蒙版,我可以毫无问题地将多边形绘制成黑色和白色。但我希望它们在一定数量的像素上逐渐在两种颜色之间过渡,比方说 50 像素(应该指定该大小)。

我遇到了 PathGradiantBrush,但找不到指定过渡区域大小的方法。使用该笔刷,过渡似乎取决于多边形的大小和形状,而不是固定大小。

绘制此类多边形的最佳方法是什么?

我查看了 MSDN 上的路径渐变画笔,发现了 the FocusScales property 我相信它可以解决您遇到的问题。

这是来自 this page 的示例,显示了 FocusScales 的使用:

// Create a path that consists of a single ellipse.
GraphicsPath path;
path.AddEllipse(0, 0, 200, 100);

// Create a path gradient brush based on the elliptical path.
PathGradientBrush pthGrBrush(&path);
pthGrBrush.SetGammaCorrection(TRUE);

// Set the color along the entire boundary to blue.
Color color(Color(255, 0, 0, 255));
INT num = 1;
pthGrBrush.SetSurroundColors(&color, &num);

// Set the center color to aqua.
pthGrBrush.SetCenterColor(Color(255, 0, 255, 255));

// Use the path gradient brush to fill the ellipse. 
graphics.FillPath(&pthGrBrush, &path);

// Set the focus scales for the path gradient brush.
pthGrBrush.SetFocusScales(0.3f, 0.8f);

// Use the path gradient brush to fill the ellipse again.
// Show this filled ellipse to the right of the first filled ellipse.
graphics.TranslateTransform(220.0f, 0.0f);
graphics.FillPath(&pthGrBrush, &path);

以及输出示例:

正如您在另一个答案中看到的那样,渐变画笔确实会使用 centered 渐变填充路径或多边形;您可以设置中心点,但它们仍然不会真正跟随多边形的边缘:

你可以通过创建一个 ColorBlendTransparent 和合适的 Positions 来影响每个色带的相对宽度,就像我对上面的结果所做的那样,但是角度朝向中心点的边缘以及它们与边界矩形的距离仍将决定它们的绝对宽度。对于多色渐变画笔示例


因此,除非您的多边形接近圆形,否则您需要采用不同的方式。

这是一个解决方案,它将遵循边缘:

使用GraphicsPath path(或者只是一个Point数组)和一个Graphics对象g它首先填充背景颜色然后用笔绘制路径宽度和透明度都在增加。为了使外边缘保持原位且不透明,我设置了 Pen.Alignment = PenAlignment.Inset。你当然可以玩数字..:[=​​22=]

g.FillPath(Brushes.MediumSeaGreen, path);

int ew = 8; // edge width

for (int i = 0; i < ew ; i++)
    using (Pen pen = new Pen(Color.FromArgb(255 - i * 255 / ew, Color.DarkSlateBlue), i ))
    {
        pen.Alignment = PenAlignment.Inset;
        g.DrawPath(pen, path);
    }

请注意,左边缘看起来有点厚,但实际上并没有;只是一种错觉..