2013-02-20 82 views
2

我目前正在嘗試使用Windows窗體應用程序在C#中進行簡單的繪圖程序。當使用ToArray函數將我的列表轉換爲數組時,我得到一個通用的「ArgumentException未處理:參數無效」錯誤。我知道我以前做過這件事,它工作得很好,有沒有什麼特別的DrawLines函數,我不知道?下面是代碼,這條線是panel1_Paint事件的最後一行。預先感謝您提供的任何幫助。將點列表轉換爲C#中的數組#

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace GetSig 
{ 
    public partial class Form1 : Form 
{ 
    bool paint = false; 
    List<Point> myPointList = new List<Point>(); 

    private void panel1_MouseDown(object sender, MouseEventArgs e) 
    { 
     paint = true; 
    } 

    private void panel1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (paint) 
     { 
      myPointList.Add(e.Location); 
      panel1.Invalidate(); 
     } 
    } 

    private void panel1_MouseUp(object sender, MouseEventArgs e) 
    { 
     paint = false; 
    } 

    private void panel1_Paint(object sender, PaintEventArgs e) 
    { 
     e.Graphics.DrawLines(Pens.Black, myPointList.ToArray()); 
    } 
} 
} 
+0

請刪除不涉及這個問題的所有代碼。 – 2013-02-20 12:52:08

+0

嘗試使用Point [] array = myPointList.ToArray()創建一個數組,並查看裏面的內容。也許你會發現一些奇怪的東西! – 2013-02-20 12:52:58

回答

0

嗯,你不能畫線沒有至少兩個點:)

if (myPointList.Count >= 2) 
{ 
    e.Graphics.DrawLines(Pens.Black, myPointList.ToArray()); 
} 
+0

非常好,非常感謝你的幫助。有趣的是,你有時候會忘記最簡單的事情! – 2013-02-20 13:12:44

0

最有可能的例外是不是從調用來ToArraye.Graphics.DrawLines

2

按照MSDN

數組中的前兩個點指定的第一行。

您的Array需要至少兩點。

+0

有趣的是,文檔沒有提到事實上發生在那裏的'ArgumentExeption'。它只是說'ArgumentNullException' ... – 2013-02-20 12:56:28

+0

@ user2091198:在向列表中添加第一個點之後,調用'Invalide'方法,它可以在下一個'MouseMove'之前誘發'Paint'處理程序。在您的答案中將'DrawLines'寫爲ken2k之前,使用'if(myPointList.Count> = 2)'。 – 2013-02-20 13:13:52