【问题标题】:Preserving pen size?保持笔的大小?
【发布时间】:2017-06-12 19:15:05
【问题描述】:

所以我正在制作一个绘画应用程序,我想知道如何保持我绘制的线条的粗细。因此,我的应用程序使用所有绘制线的点列表,并在每次用户绘制新线时再次绘制它们。现在我有一个问题,当我改变笔的大小时,所有线条的大小都会改变,因为它们都被重绘了。

我的代码:

        //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() 来更改笔的大小,但我怎样才能保留线宽?

【问题讨论】:

标签: c# graphics


【解决方案1】:

代替List&lt;List&lt;Point&gt;&gt;,编写一个具有List&lt;Point&gt; 和笔宽的类,并使用它的列表。我们也会添加颜色,但你可以省略它。

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 在 cmets 中指出的那样,您也可以为 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);
}

编写十几个不同的子类来绘制圆、弧、笑脸猫等等。

【讨论】:

  • 你是个天才!谢谢。
  • 事实上,您甚至可以在这个自定义类中添加一个Draw 方法来处理使用正确的Pen 绘制线条。
  • @Kyle 谢谢,我补充了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多