c# - 使用 FillPath 创建带孔的多边形

标签 c# geometry drawing draw gdi+

我有以下代码:

using (var gp = new GraphicsPath())
{    
    var outer = new PointF[outerpoly.Count];
    for (int i = 0; i < outerpoly.Count; i++)
    {
        outer[i] = new PointF(((int)(scale * outerpoly[i].X - xmin)), (int)(scale * (outerpoly[i].Y + -ymin)));
    }
    gp.AddPolygon(outer);
    foreach (var hole in insideholes)
    {
        if (hole.Count < 3) continue;
        var inner = new PointF[hole.Count];
        for (int i = 0; i < hole.Count; i++)
        {
            inner[i] = new PointF(((int)(scale * hole[i].X - xmin)), (int)(scale * (hole[i].Y + -ymin)));
        }
        gp.AddPolygon(inner);
    }
    Graphics.FromImage(e).FillPath(color, gp);
}

其中,outerpoly 是表示多边形外边界的整数点列表(xy 对),而内孔是表示多边形外部边界的整数点列表列表。多边形侧面的孔。

现在这段代码应该绘制一个带有许多孔的多边形。内部和外部可以作为值给出的示例:

outer
{System.Drawing.PointF[4]}
    [0]: {X=-289, Y=971}
    [1]: {X=-289, Y=0}
    [2]: {X=734, Y=971}
    [3]: {X=-289, Y=971}
inner
{System.Drawing.PointF[4]}
    [0]: {X=-158, Y=797}
    [1]: {X=189, Y=568}
    [2]: {X=-158, Y=568}
    [3]: {X=-158, Y=797}

现在这段代码的结果是只绘制外部并且忽略孔。知道为什么吗?

该代码基于 question .

当尝试使用排除方法时,如下所示:

var outer = new PointF[outerpoly.Count];
for (int i = 0; i < outerpoly.Count; i++)
{
    outer[i] = new PointF(((int)(scale * outerpoly[i].X - xmin)), (int)(scale * (outerpoly[i].Y + -ymin)));
}
var gp = new GraphicsPath();
gp.AddPolygon(outer);
Region rr = new Region(gp);

foreach (var hole in insideholes)
{
    if (hole.Count < 3) continue;
    var inner = new PointF[hole.Count];
    for (int i = 0; i < hole.Count; i++;)
    {
        inner[i] = new PointF(((int)(scale * hole[i].X - xmin)), (int)(scale * (hole[i].Y + -ymin)));
    }
    var gpe = new GraphicsPath();
    gpe.AddPolygon(inner);
    Region.Exclude(gpe);
    gpe.Dispose();
}
gp.Dispose();

Graphics.FromImage(e).FillRegion(color, rr);
rr.Dispose();

这在Region.Exclude(gpe);线上崩溃了,没有异常(exception),只是突然崩溃到桌面。

最佳答案

我通常会先加入所有内部图形,然后使用外部图形和内部图形创建一个 GraphicsPath。
默认填充模式会填充孔。

我使用 Clipper 来连接多边形:
http://www.angusj.com/delphi/clipper.php

如果需要裁剪外部,则应该创建一个裁剪区域:
https://msdn.microsoft.com/en-us/library/155t36zz(v=vs.110).aspx

        Graphics g = e.Graphics;
        var path = new GraphicsPath();

        Rectangle outer = new Rectangle(100, 100, 300, 300);
        Rectangle inner = new Rectangle(150, 150, 200, 200);

        path.AddRectangle(outer);
        path.AddRectangle(inner);

        var brush = new SolidBrush(Color.Blue);
        g.FillPath(brush, path);

Hole

关于c# - 使用 FillPath 创建带孔的多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34591226/

相关文章:

c# - 在 .NET 中以编程方式使用制表符

sql - 与 Sql Geometry 字段不同的棘手 sql

c++ - 将圆或样条拟合到一堆 3D 点中

java - 创建一个 Squircle

c# - 添加类到@Html.ActionLink

c# - 在 Windows 窗体中隐藏标签需要 244 毫秒

c# - 取消记住远程调试器凭据

python - 质心 Voronoi 镶嵌

python - 在 Opencv 中绘制断裂线(点线/虚线)

c# - 用鼠标绘图会导致像素之间出现间隙