2

So I'm making a paint app, and I'm wondering how I can preserve the thickness of lines I draw. So my app uses a list of a list of points of all lines drawn, and draws them all again every time a new line is drawn by the user. Now I have one problem, when I change the pen size, the size of ALL the lines change, as they're all getting redrawn.

My code:

        //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();

I know one can use Pen.Width() to change the pen size during the loop but how can I preserve line widths?

Chai_Latte
  • 59
  • 4
  • You may want to study [this post about a DrawAction class](https://stackoverflow.com/questions/28714411/update-a-drawing-without-deleting-the-previous-one/28716887?s=6|0.1736#28716887) – TaW Jun 12 '17 at 19:29

1 Answers1

3

Instead of List<List<Point>>, write a class that has a List<Point> and a pen width, and use a list of that. We'll throw in color as well, but you can omit that.

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

Make previousPoints a list of those:

private List<MyPointList> previousPoints;

And loop through:

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

The using block disposes the pens.

As Kyle notes in comments, you could give MyPointList a method that does the drawing, too.

In fact, you could write a base class with an abstract or virtual Draw(Graphics g) method:

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]);
        }
    }
}

...and use like so:

private List<MyDrawingThing> previousPoints;

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

Write a dozen different subclasses that draw circles, arcs, lolcats, whatever.