我正在尝试从自定义的点列表构建一个简单的多边形PathGeometry。我在msdn website上找到了以下代码,它似乎运行正常,只需对循环进行简单修改并添加LineSegments,但看起来似乎是一个相对简单的任务,看起来像是一个非常糟糕的混乱。还有更好的方法吗?
PathFigure myPathFigure = new PathFigure();
myPathFigure.StartPoint = new Point(10, 50);
LineSegment myLineSegment = new LineSegment();
myLineSegment.Point = new Point(200, 70);
PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
myPathSegmentCollection.Add(myLineSegment);
myPathFigure.Segments = myPathSegmentCollection;
PathFigureCollection myPathFigureCollection = new PathFigureCollection();
myPathFigureCollection.Add(myPathFigure);
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures = myPathFigureCollection;
Path myPath = new Path();
myPath.Stroke = Brushes.Black;
myPath.StrokeThickness = 1;
myPath.Data = myPathGeometry;
答案 0 :(得分:1)
您可以将其包装在一个函数中,也可以合并一些语句。
Path makePath(params Point[] points)
{
Path path = new Path()
{
Stroke = Brushes.Black,
StrokeThickness = 1
};
if (points.Length == 0)
return path;
PathSegmentCollection pathSegments = new PathSegmentCollection();
for (int i = 1; i < points.Length; i++)
pathSegments.Add(new LineSegment(points[i], true));
path.Data = new PathGeometry()
{
Figures = new PathFigureCollection()
{
new PathFigure()
{
StartPoint = points[0],
Segments = pathSegments
}
}
};
return path;
}
然后你可以这样称呼它:
Path myPath = makePath(new Point(10, 50), new Point(200, 70));