为什么更改笔尺寸不起作用?

时间:2017-06-11 11:16:06

标签: c# graphics

所以这是我的代码:

float penSize = 1;
        Pen p = new Pen(Color.Black, penSize);
        e.Graphics.DrawLine(p , new Point(0 , 0) , new Point(100, 100));
        penSize = 5;
        e.Graphics.DrawLine(p, new Point(0, 0), new Point(50, 150));
        penSize = 10;
        e.Graphics.DrawLine(p, new Point(0, 0), new Point(30, 200));
        p.Dispose();

这是我的Panel Paint事件。 我认为这将输出3条线,所有不同的厚度(1,5和10)。

然而它只是输出: All lines of same thickness?

谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:1)

您需要为每个尺寸创建一个Pen实例。 Pen实例不会保留对浮动的引用,因此更改penSize不会影响已创建的Pen实例。这是设计,浮点数是值类型,它们的值被复制,而不是被引用。

using( Pen p1 = new Pen(Color.Black, 1))
{
  e.Graphics.DrawLine(p1 , new Point(0 , 0) , new Point(100, 100));
}
using(Pen p5 = new Pen(Color.Black, 5))
{
    e.Graphics.DrawLine(p5, new Point(0, 0), new Point(50, 150));
}
using(Pen p10 = new Pen(Color.Black, 10))
{
    e.Graphics.DrawLine(p10, new Point(0, 0), new Point(30, 200));
}

作为替代方案,您可以按照kennyxyz在评论中的建议设置单个Pen实例的Width属性:

// start with a Width of 1 
using( Pen pen = new Pen(Color.Black, 1))
{
  e.Graphics.DrawLine(pen , new Point(0 , 0) , new Point(100, 100));
  pen.Width = 5;
  e.Graphics.DrawLine(pen, new Point(0, 0), new Point(50, 150));
  pen.Width = 10;
  e.Graphics.DrawLine(pen, new Point(0, 0), new Point(30, 200));
}  // Dispose is called here

你的结果:

drawing