如何用C#绘制带有线宽的虚线

2025-04-17 02:02:02
推荐回答(2个)
回答1:

画线时定义pen的宽度就可以了,示例如下:

在窗口的print事件中给窗体画虚线:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;  //Graphics g =  this.CreateGraphics();
    Pen p = new Pen(Color.Black, 2);  //黑色画笔 2宽度.
    p.DashStyle = System.Drawing.Drawing2D.DashStyle.DashDot; //系统中的虚线样式
    g.DrawLine(p, 10, 10, 500, 10);
    p = new Pen(Color.Black, 4);  //黑色画笔 4宽度.
    p.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom; //自定义样式
    p.DashPattern = new float[] { 5, 5 };
    g.DrawLine(p, 10, 30, 500, 30);
    p = new Pen(Color.Black, 8);  //黑色画笔 8宽度.
    p.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
    p.DashPattern = new float[] { 5, 5 };
    g.DrawLine(p, 10, 50, 500, 50);
}

效果如下:

Pen 构造函数 (Color, Single)说明:
用指定的 Color 和 Width 属性初始化 Pen 类的新实例。
命名空间:  System.Drawing
程序集:  System.Drawing(在 System.Drawing.dll 中)
语法
public Pen(
    Color color,
    float width
)
参数
color
类型:System.Drawing.Color
Color  结构,指示此 Pen 的颜色。
width
类型:System.Single
指示此 Pen 的宽度的值。
备注
 Color  属性设置为 color 参数指定的颜色。 Width  属性设置为在 width 参数中指定的值。 width 为 0 将导致 Pen 的绘图效果呈现为宽度为 1 的形式。

回答2:

Graphics g = e.Graphics;  //Graphics g =  this.CreateGraphics();

           

            Pen p = new Pen(Color.Black, 2);  //黑色画笔 2宽度.

            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;

            p.DashPattern = new float[] { 5, 5 };

            g.DrawLine(p, 10, 150, 500, 150);


            p = new Pen(Color.Black, 5);  //黑色画笔 5宽度.

            p.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;

            p.DashPattern = new float[] { 5, 5 };

            g.DrawLine(p, 10, 170, 500, 170);