2014-12-04 38 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]); 
}