我试图保存我绘制的三角形,然后在前一个三角形仍然存在的情况下再次绘制。我这样做是在矩形,正方形,圆形和椭圆形中完成的。我不知道为什么它不会出现在Triangle中。代码有什么问题吗?
这就是我绘制和“保存(不工作)”的方式
形状类别
public void DrawTriangle(Color c, int stroke,PointF[] tpoints, float w, Graphics g)
{
this.width = w;
this.strokeThickness = stroke;
this.tPoints = tpoints;
g.InterpolationMode = InterpolationMode.High;
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawPolygon(new Pen(c, stroke), tpoints);
}
表格1
public void DrawTriangle()
{
tC = Color.Red;
strokeTriangle = trackBar_Stroke.Value;
tW = Convert.ToInt32((Convert.ToInt32(tbox_Width.Text) * 96) / 25.4);
tH = (Convert.ToInt32((tW * (Math.Sqrt(3))) / 2));
tX = (pictureBox_Canvass.Width - tW) / 2;
tY = ((pictureBox_Canvass.Width - (tH)) / 2) + tH;
float angle = 0;
t_Points[0].X = tX;
t_Points[0].Y = tY;
t_Points[1].X = (float)(tX + tW * Math.Cos(angle));
t_Points[1].Y = (float)(tY + tW * Math.Sin(angle));
t_Points[2].X = (float)(tX + tW * Math.Cos(angle - Math.PI / 3));
t_Points[2].Y = (float)(tY + tW * Math.Sin(angle - Math.PI / 3));
}
public void AcceptTriangle()
{
Shape shape = new Shape();
tC = Color.Gray;
shape.strokeThickness = strokeTriangle;
shape.width = tW;
shape.x = tX;
shape.y = tY;
shape.tPoints = t_Points;
s._triangle.Add(shape);
}
s.DrawTriangle(tC, strokeTriangle,t_Points, tX, tY, tW, e.Graphics);
这就是我的迭代方式。
public List<Shape> _triangle = new List<Shape>();
foreach(Shape shapes3 in s._triangle)
{
shapes3.DrawTriangle(shapes3.color, shapes3.strokeThickness, shapes3.tPoints, shapes3.width, e.Graphics);
}
答案 0 :(得分:1)
在代码的两点处,您编写了这样的数组分配:
this.tPoints = tpoints;
..以及
shape.tPoints = t_Points;
一个常见的错误是假设这会创建一个包含数据的数组。 没有。所有要做的就是将数组变量指向到之前存在的数组。
不重复数据。因此,当您覆盖数据或清除数据时,“新”数组现在指向更改或清除的数据。
所以所有,您的对象具有非常相同的点。
要正确创建数据的实际副本!
最简单的方法是像这样添加一个ToArray()
调用:
this.tPoints = tpoints.ToArray();
..以及
shape.tPoints = t_Points.ToArray();
要重申:
int[] p1 = new int[2] { 23, 42 }; // Now we have one array.
int[] p2 = new int[2] { 3, 2 }; // Now we have two arrays.
p2 = p1; // Now we have only one array again.
p2[1]=1234; // Now p1[1] is 1234