如何:设置笔的宽度和对齐方式

创建 Pen时,您可以将笔宽作为传递给构造函数的参数之一。 还可以使用 Pen 类的 Width 属性更改笔宽度。

理论线的宽度为 0。 绘制宽度为 1 像素的线条时,像素以理论线为中心。 如果绘制的线条宽度超过一个像素,则像素要么以理论线为中心,要么显示在理论线的一侧。 您可以设置Pen的笔对齐属性,以确定使用该笔绘制的像素如何相对于理论线进行定位。

以下代码示例中显示的值 CenterOutsetInsetPenAlignment 枚举的成员。

下面的代码示例将绘制这根线两次:一次用黑色宽度为1的笔,一次用绿色宽度为10的笔。

改变笔的宽度

  • Alignment 属性的值设置为 Center(默认值),以指定用绿色笔绘制的像素将集中在理论线上。 下图显示了结果线。

    一条突出显示绿色的黑色细线。

    下面的代码示例绘制一个矩形两次:一次使用宽度为 1 的黑色笔,一次绘制宽度为 10 的绿色笔。

    Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
    Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
    greenPen.Alignment = PenAlignment.Center;
    
    // Draw the line with the wide green pen.
    e.Graphics.DrawLine(greenPen, 10, 100, 100, 50);
    
    // Draw the line with the thin black pen.
    e.Graphics.DrawLine(blackPen, 10, 100, 100, 50);
    
    Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1)
    Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10)
    greenPen.Alignment = PenAlignment.Center
    
    ' Draw the line with the wide green pen.
    e.Graphics.DrawLine(greenPen, 10, 100, 100, 50)
    
    ' Draw the line with the thin black pen.
    e.Graphics.DrawLine(blackPen, 10, 100, 100, 50)
    
    

更改笔的对齐方式

  • Alignment 属性的值设置为 Center,以指定用绿色笔绘制的像素将居中矩形的边界上。

    下图显示了生成的矩形:

    用黑色细线绘制的矩形,带突出显示的绿色。

    Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1);
    Pen greenPen = new Pen(Color.FromArgb(255, 0, 255, 0), 10);
    greenPen.Alignment = PenAlignment.Center;
    
    // Draw the rectangle with the wide green pen.
    e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50);
    
    // Draw the rectangle with the thin black pen.
    e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50);
    
    Dim blackPen As New Pen(Color.FromArgb(255, 0, 0, 0), 1)
    Dim greenPen As New Pen(Color.FromArgb(255, 0, 255, 0), 10)
    greenPen.Alignment = PenAlignment.Center
    
    ' Draw the rectangle with the wide green pen.
    e.Graphics.DrawRectangle(greenPen, 10, 100, 50, 50)
    
    ' Draw the rectangle with the thin black pen.
    e.Graphics.DrawRectangle(blackPen, 10, 100, 50, 50)
    
    

创建内嵌笔

  • 通过修改前面的代码示例中的第三个语句来更改绿色笔的对齐方式,如下所示:

    greenPen.Alignment = PenAlignment.Inset;
    
    greenPen.Alignment = PenAlignment.Inset
    
    

    现在,宽绿色线条中的像素显示在矩形内部,如下图所示:

    用黑色线条绘制的矩形,里面有宽绿色线。

另请参阅