2017-06-12 111 views
2

所以我正在製作一個繪畫應用程序,我想知道如何保留我繪製的線條的粗細。因此,我的應用程序使用繪製的所有線條的列表的列表,並在每次用戶繪製新線條時再次繪製它們。現在我遇到了一個問題,當我改變筆的大小時,所有行的大小都會改變,因爲它們都被重繪了。保留筆的大小?

我的代碼:

 //Create new pen 
     Pen p = new Pen(Color.Black, penSize); 
     //Set linecaps for start and end to round 
     p.StartCap = LineCap.Round; 
     p.EndCap = LineCap.Round; 
     //Turn on AntiAlias 
     e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; 
     //For each list of line coords, draw all lines 
     foreach (List<Point> lstP in previousPoints) 
     { 
      e.Graphics.DrawLine(p, lstP[0], lstP[1]); 
     } 
     p.Dispose(); 

我知道一個可以使用Pen.Width()的循環過程中改變畫筆大小,但我怎麼能保存線寬?

+0

你可能想研究[這篇文章關於DrawAction類](https://stackoverflow.com/questions/28714411/update-a-drawing-without-deleting-the-previous-one/28716887?s=6 | 0.1736#28716887) – TaW

回答

3

而不是List<List<Point>>,寫一個具有List<Point>和筆寬度的類,並使用它的列表。我們也會着色,但是你可以忽略它。

public class MyPointList { 
    public List<Point> Points { get; set; } 
    public float PenWidth { get; set; } 
    public Color Color { get; set; } 
} 

讓previousPoints人的名單:

private List<MyPointList> previousPoints; 

並遍歷:

foreach (MyPointList lstP in previousPoints) { 
    using (var p = new Pen(lstP.Color, lstP.PenWidth)) { 
     e.Graphics.DrawLine(p, lstP.Points[0], lstP.Points[1]); 
    } 
} 

using塊處置筆。

正如Kyle在評論中指出的那樣,您也可以給MyPointList一個繪製圖的方法。

事實上,你可以寫一個基類抽象或虛擬Draw(Graphics g)方法:

public abstract class MyDrawingThing { 
    public abstract void Draw(Graphics g); 
} 

public class MyPointList : MyDrawingThing { 
    public List<Point> Points { get; set; } 
    public float PenWidth { get; set; } 
    public Color Color { get; set; } 

    public override void Draw(Graphics g) { 
     using (var p = new Pen(Color, PenWidth)) { 
      g.DrawLine(p, Points[0], Points[1]); 
     } 
    } 
} 

...並使用像這樣:

private List<MyDrawingThing> previousPoints; 

foreach (MyDrawingThing thing in previousPoints) { 
    thing.Draw(e.Graphics); 
} 

編寫畫十幾個不同的子類圓圈,弧形,大嘴棒,不管。

+0

你是個天才!謝謝。 –

+2

事實上,你甚至可以在這個自定義類中添加一個'Draw'方法來處理用正確的'Pen'畫線。 – Kyle

+1

@凱爾謝謝,我補充說。 –