如何在对象上绘制虚线?

时间:2011-05-23 17:17:36

标签: c# winforms user-interface drawing 2d

我在Windows窗体上的控件上画了一行,如下所示:

            // Get Graphics object from chart
            Graphics graph = e.ChartGraphics.Graphics;

            PointF point1 = PointF.Empty;
            PointF point2 = PointF.Empty;

            // Set Maximum and minimum points
            point1.X = -110;
            point1.Y = -110;
            point2.X = 122;
            point2.Y = 122;

            // Convert relative coordinates to absolute coordinates.
            point1 = e.ChartGraphics.GetAbsolutePoint(point1);
            point2 = e.ChartGraphics.GetAbsolutePoint(point2);

            // Draw connection line
            graph.DrawLine(new Pen(Color.Yellow, 3), point1, point2);

我想知道是否可以绘制虚线(虚线)而不是常规实线?

5 个答案:

答案 0 :(得分:30)

一旦你figure out the formatting定义了破折号,这很简单:

float[] dashValues = { 5, 2, 15, 4 };
Pen blackPen = new Pen(Color.Black, 5);
blackPen.DashPattern = dashValues;
e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5));

float数组中的数字表示不同颜色的破折号长度。因此,对于简单的两个像素(黑色)和两个关闭,你的aray看起来像:{2,2}然后重复模式。如果您想要5宽的短划线,空格为2像素,则可以使用{5,2}

在您的代码中,它看起来像:

// Get Graphics object from chart
Graphics graph = e.ChartGraphics.Graphics;

PointF point1 = PointF.Empty;
PointF point2 = PointF.Empty;

// Set Maximum and minimum points
point1.X = -110;
point1.Y = -110;
point2.X = 122;
point2.Y = 122;

// Convert relative coordinates to absolute coordinates.
point1 = e.ChartGraphics.GetAbsolutePoint(point1);
point2 = e.ChartGraphics.GetAbsolutePoint(point2);

// Draw (dashed) connection line
float[] dashValues = { 4, 2 };
Pen dashPen= new Pen(Color.Yellow, 3);
dashPen.DashPattern = dashValues;
graph.DrawLine(dashPen, point1, point2);

答案 1 :(得分:9)

我认为您可以通过更改用于绘制线条的笔来实现此目的。 因此,将示例中的最后两行替换为:

        var pen = new Pen(Color.Yellow, 3);
        pen.DashStyle = DashStyle.Dash;
        graph.DrawLine(pen, point1, point2);

答案 2 :(得分:7)

Pen有一个公共属性,定义为

public DashStyle DashStyle { get; set; }

如果要绘制虚线,可以设置DasStyle.Dash

答案 3 :(得分:3)

Pen。DashPattern会这样做。 Look here for an example

答案 4 :(得分:2)

更现代的C#:

var dottedPen = new Pen(Color.Gray, width: 1) { DashPattern = new[] { 1f, 1f } };
相关问题