使用CombinedGeometry在wpf中连接两个多边形

时间:2014-05-29 07:01:07

标签: c# wpf geometry

我正在使用CombinedGeometry将几个矩形合并在一起。这是我用过的代码。

它有点冗长,但它的要点是这里将两个矩形组合成一个几何体,最终的几何体传递给Path.Data

现在当我合并这些时,如下图所示,当两个矩形相互连接时,关节相当难看。我想知道是否有办法让它看起来更漂亮,如红色标记所示?

enter image description here

<Canvas Width="1000" Height="1000">
    <Path Stroke="Black" StrokeThickness="1" Fill="Transparent" x:Name="MyPath" >
    </Path>
</Canvas>

public class MyRect
{
    public double X1 { get; set; }
    public double Y1 { get; set; }
    public double X2 { get; set; }
    public double Y2 { get; set; }
    public double X3 { get; set; }
    public double Y3 { get; set; }
    public double X4 { get; set; }
    public double Y4 { get; set; }
}

var cg = new CombinedGeometry { GeometryCombineMode = GeometryCombineMode.Union };

var rect1 = new MyRect { X1 = 500, Y1 = 120, X2 = 1000, Y2 = 120, X3 = 1000, Y3 = 80, X4 = 500, Y4 = 80 };
var rect2 = new MyRect { X1 = 480, Y1 = 100, X2 = 480, Y2 = 200, X3 = 520, Y3 = 200, X4 = 520, Y4 = 100 };

var list = new List<MyRect>
{
    rect1, rect2
};

var geometry = new PathGeometry();

var myRec = list[0];
var la = new LineSegment { Point = new Point(myRec.X2, myRec.Y2) };
var lb = new LineSegment { Point = new Point(myRec.X3, myRec.Y3) };
var lc = new LineSegment { Point = new Point(myRec.X4, myRec.Y4) };
var pathFigure = new PathFigure
{
    StartPoint = new Point(myRec.X1, myRec.Y1),
    Segments = { la, lb, lc }
};

var path = new PathGeometry { Figures = { pathFigure } };
cg.Geometry1 = path;
for (var i = 1; i < list.Count; i++)
{
    myRec = list[i];

    la = new LineSegment { Point = new Point(myRec.X2, myRec.Y2) };
    lb = new LineSegment { Point = new Point(myRec.X3, myRec.Y3) };
    lc = new LineSegment { Point = new Point(myRec.X4, myRec.Y4) };
    pathFigure = new PathFigure
    {
        StartPoint = new Point(myRec.X1, myRec.Y1),
        Segments = { la, lb, lc }
    };

    path = new PathGeometry { Figures = { pathFigure } };
    cg.Geometry2 = path;

    geometry = cg.GetFlattenedPathGeometry();
    cg.Geometry1 = geometry;
}
MyPath.Data = geometry;

1 个答案:

答案 0 :(得分:1)

走合并路径并合并边缘对,其中两条边比一些X短?

X可以设置为低于任何矩形边长度的东西,因此您不会改变原始特征,只需清理图片中的小文物。

取决于您的源数据以及是否有任何非平凡的案例。