我想绘制以下红色多边形:
问题是如果我使用这样的东西:
Polygon poly = new Polygon();
poly.StrokeThickness = 2;
poly.Stroke = Brushes.Black;
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
poly.Points = points;
然后多边形总是被“填充”,在上面的例子中绘制了红色和绿色的多边形。
我已经尝试将 4 个“内部”点添加到 PointCollection,但是没有绘制任何内容。那么我该如何实现呢?
我尝试了大卫提出的解决方案:
for (int n = 0; n < this.NumberOfRevisions; n++)
{
Path path = new Path();
CombinedGeometry geometry = new CombinedGeometry();
geometry.GeometryCombineMode = GeometryCombineMode.Union;
Polygon poly = new Polygon();
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
poly.Points = points;
geometry.Geometry1 = poly.RenderedGeometry;
geometry.Geometry2 = poly.RenderedGeometry;
path.Data = geometry;
polygons.Add(poly);
paths.Add(path);
}
这只是一个测试,但我认为我应该得到与以前相同的结果,但它没有绘制任何东西。我的代码有问题吗?
最佳答案
如果您想拥有 2 个独立的形状,并且绿色的形状可能像您在评论中所说的那样透明,那么最好的方法是使用组合几何体:
http://msdn.microsoft.com/en-en/library/ms653071%28v=VS.85%29.aspx
借助于此,您可以先创建绿色几何体,然后通过从红色几何体中减去绿色(或其副本)来创建孔,从而创建红色。
所以基本上:
- 红色形状,普通
- 它上面的绿色形状,PLAIN
- 从红色形状中减去绿色形状或其副本 >> 红色形状中的洞
这样你就可以得到你想要的效果
在 Xaml 中更容易完成,在 C# 中稍微复杂一些,但仍然可行。
编辑:将组合几何设置为路径的数据:
Path myPath = new Path();
CombinedGeometry myCombinedGeometry = new CombinedGeometry()
// here you set the combinedGeometry's geometries to create the shape you want
myPath.Data = myCombinedGeometry;
myGrid.Children.Add(myPath);
顺便说一下,PATH 将是您为颜色设置 Fill/Stroke 属性的地方,而不是内部几何图形。 (请参阅上面链接中 xaml 中的示例,您基本上只需将代码翻译成 C#)
编辑2:
不要忘记在路径上设置填充:
for (int n = 0; n < this.NumberOfRevisions; n++)
{
CombinedGeometry geometry = new CombinedGeometry() { GeometryCombineMode = GeometryCombineMode.Union };
PointCollection points = new PointCollection();
for (int i = 0; i < this.NumberOfMetrics; i++)
{
points.Add(new Point(MAX_VALUE - this.Metrics[n, i] * Math.Cos(DegreeToRadian(i * (360 / (this.NumberOfMetrics)))), MAX_Y_GUI - this.Metrics[n, i] * Math.Sin(DegreeToRadian(i * (360 / (this.NumberOfMetrics))))));
}
Polygon poly = new Polygon();
poly.Points = points;
geometry.Geometry1 = poly.RenderedGeometry;
geometry.Geometry2 = poly.RenderedGeometry;
polygons.Add(poly);
paths.Add(path = new Path() { Data = geometry, Fill = Brushes.Red, Stroke = Brushes.Transparent });
}
关于c# - WPF:如何绘制这个多边形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5011656/