我想绘制以下红色多边形:
问题是如果我使用这样的东西:
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);
}
这只是一个测试,但我知道我应该得到与以前相同的结果,但它没有被绘制。我的代码有问题吗?
答案 0 :(得分:5)
如果您想拥有2个独立的形状,并且绿色的形状可能是您在评论中所说的透明,那么最好的方法是使用组合几何:
http://msdn.microsoft.com/en-en/library/ms653071%28v=VS.85%29.aspx
借助于此,您可以先创建绿色几何体,然后通过从红色几何体中减去绿色(或其副本)来创建红色几何体。
基本上是这样的:
在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#)
<强> EDIT2:强>
不要忘记在路径上设置填充:
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 });
}