如何在对象上绘制虚线?

l--*_*''' 14 c# user-interface drawing 2d winforms

我在我的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);
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*sik 32

一旦找出定义破折号的格式,这很简单:

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));
Run Code Online (Sandbox Code Playgroud)

float数组中的数字表示不同颜色的破折号长度.因此,对于一个简单的2像素(黑色)和两个关闭你的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);
Run Code Online (Sandbox Code Playgroud)


Gus*_*ori 9

我认为你可以通过改变用来绘制线条的笔来实现这一目标.因此,将示例中的最后两行替换为:

        var pen = new Pen(Color.Yellow, 3);
        pen.DashStyle = DashStyle.Dash;
        graph.DrawLine(pen, point1, point2);
Run Code Online (Sandbox Code Playgroud)


cry*_*ted 7

Pen有一个公共财产,定义为

public DashStyle DashStyle { get; set; }
Run Code Online (Sandbox Code Playgroud)

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