我正在绘制一个带有坐标的不规则多边形,绘制它是有效的,当我试图计算错误发生的区域和质心时。
命名空间 WpfApplication3
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Draw polygon
public void Window_Loaded(object sender, RoutedEventArgs e)
{
Point[] curvePoints =
{
new Point(10, 10),
new Point(13, 11),
new Point(15, 30),
new Point(17, 10),
new Point(20, 10),
new Point(30, 15),
new Point(30, 30),
new Point(60, 40),
new Point(65, 55),
new Point(40, 60),
new Point(40, 65),
new Point(58, 70),
new Point(60, 60),
new Point(90, 60),
new Point(90, 85),
new Point(70, 61),
new Point(60, 85),
new Point(30, 85),
new Point(12, 80),
new Point(12, 78),
new Point(16, 75),
new Point(13, 68),
new Point(17, 65),
new Point(6, 62),
new Point(16, 60),
new Point(28, 56),
new Point(27, 45),
new Point(15, 32),
new Point(15, 50),
new Point(5, 50),
new Point(10, 40)
};
var pointCollection = new PointCollection(curvePoints);
var polygon = new Polygon
{
Stroke = Brushes.GreenYellow,
StrokeThickness = 1,
Fill = Brushes.Blue,
Points = pointCollection
};
const int cx = 200;
const int cy = 150;
polygon.Measure(new Size(cx, cy));
polygon.Arrange(new Rect(0, 0, cx, cy));
RenderTargetBitmap bmp = new RenderTargetBitmap(cx, cy, 120, 96, PixelFormats.Pbgra32);
bmp.Render(polygon);
_image.Source = bmp;
}
// Calculate area
class Point { double X, Y; }
double PolygonArea(Point[] polygon)
{
int i, j;
double area = 0;
for (i=0; i < polygon.Length; i++)
{
j = (i + 1) % polygon.Length;
area += polygon[i].X * polygon[j].Y;
area += polygon[i].Y * polygon[j].X;
}
area /= 2;
return (area < 0 ? -area : area);
}
// Calculate Centroid
Point centroid =
polygon.points.Aggregate(
new { xSum = 0.0, ySum = 0.0, n = 0 },
(acc, p) => new
{
xSum = acc.xSum + p.X,
ySum = acc.ySum + p.Y,
n = acc.n + 1
},
acc => new Point(acc.xSum / acc.ySum / acc.n));
public static object polygon { get; private set; }
}
}
经常出现的主要错误是 CS1729:MainWindow.Point 不包含采用 2 个参数的构造函数。
所以我猜我需要一个带有 2 个参数的构造函数,我只是不知道如何在 MainWindow 中添加一个。
计算质心 CS1061 中出现另一个错误:对象没有“点”的定义,也没有“点”的扩展方法。(使用或组装可能会丢失?)
关于如何解决这个问题的任何想法?谢谢!