2014-12-04 37 views
-4

我让Point数组指定某个点,但我无法在for循环中访问它们。请问有什么可以帮助我?我不能使用Point [] for循环

Point[] _points; 
private Point[] Points() 
{ 
    Rectangle rc = ClientRectangle; 
    Point[] _points=new Point[] 
    { 
     new Point{X=0,Y=ClientRectangle.Height/2}, 
     new Point{X=ClientRectangle.Width*22/277,Y=0}, 
     new Point{X=ClientRectangle.Width*68/277,Y=ClientRectangle.Height}, 
     new Point{X=ClientRectangle.Width*115/277,Y=0}, 
     new Point{X=ClientRectangle.Width*161/277,Y=ClientRectangle.Height}, 
     new Point{X=ClientRectangle.Width*206/277,Y=0}, 
     new Point{X=ClientRectangle.Width*254/277,Y=ClientRectangle.Height}, 
     new Point{X=ClientRectangle.Width,Y=ClientRectangle.Height/2} 
    }; 

    return _points;    
} 

protected override void OnPaint(PaintEventArgs pe) 
{ 
    Graphics gfx = pe.Graphics; 
    Pen kalem = new Pen(Color.Black); 
    for (int i = 0; i < _points.Length; i++) 
    { 
     gfx.DrawLine(kalem,_points[i],_points[i].Y); =======>>>ERROR HERE 
    }    
} 
+1

你得到的错误是什么? – craig1231 2014-12-04 12:54:32

+3

更多关注错误(你应该包括在你的问题中)告诉你什么。你忽略了一些非常明显的东西。 – hvd 2014-12-04 12:54:34

+0

你在'OnPaint()'函数之前调用'Points()'函数吗? – Sander 2014-12-04 12:55:07

回答

2

在声明中的函数变量(_points)重写你的属性的范围。您粘贴的代码从不将任何东西赋值给_points,这意味着该数组是空的。

编辑: 由于该方法将PointF作为参数,而_point [i] .Y是一个int,所以不能传递_point [i] .Y。

+0

这是一个合理的猜测,并且可能是错误的事情之一。不过,这可能不是答案:它可能意味着问题中缺少分配给“_points”的代码。例如,构造函数可能包含'_points = Points();'。 – hvd 2014-12-04 12:57:11

+0

此处的错误http://i.imgur.com/yKtKLr8.png – 2014-12-04 12:57:41

+0

顺便说一句我想让自定义控件不是类 – 2014-12-04 13:05:11

0
gfx.DrawLine(kalem,_points[i],_points[i].Y) 

这里,应该通过_points [I] .X与_points [I] .Y我猜

+1

我也这么认为,但'DrawLine'需要两个'PointF' – juharr 2014-12-04 13:01:09

0

我想这是你真正想要的东西。

for (int i = 0; i < _points.Length - 1; i++) 
{ 
    gfx.DrawLine(kalem,_points[i],_points[i+1]); 
} 

这将引起从所述第一点的线到第二然后从第二到THRID等。如果您需要关闭形状,请在for循环后面添加以下内容。

// No point in drawing a closing line if there are not at least 3 points. 
if(_points.Length > 2) 
{ 
    gfx.DrawLine(kalem,_points[_points.Length - 1],_points[0]); 
}