如何在一个物体上绘制虚线?

19

我正在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);
我想知道是否可以绘制虚线(点线)而不是常规实线?
6个回答

40

一旦你理解定义破折号的格式,这就变得非常简单了:

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));

浮点数数组中的数字表示不同颜色的虚线长度。因此,如果您想要一个 2 像素的黑色简单虚线,并且每个虚线之间有两个像素的空白,则您的数组将如下所示:{2,2} 然后该模式重复。如果您想要带有 2 个像素空白的 5 像素宽度的虚线,则应使用 {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);

非常感谢。你能向我展示如何将这个代码整合到我的程序中吗? - Alex Gordon
请注意我的编辑。但要注意的是,我没有通过编译器运行它,因此可能会出现语法和意图错误。无论如何,这应该能让您接近目标。 - Paul Sasik

13
我认为你可以通过更改画线时使用的笔来实现这一点。因此,将示例中的最后两行替换为:
        var pen = new Pen(Color.Yellow, 3);
        pen.DashStyle = DashStyle.Dash;
        graph.DrawLine(pen, point1, point2);

7

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

public DashStyle DashStyle { get; set; }

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


3

2
在更现代的 C# 中:
var dottedPen = new Pen(Color.Gray, width: 1) { DashPattern = new[] { 1f, 1f } };

0
回答这个关于使用代码后台生成虚线的问题:
        Pen dashPenTest = new(Brushes.DodgerBlue, 1);

        Line testLine = new()
        {
            Stroke = dashPenTest.Brush, //Brushes.Aqua,
            StrokeThickness = dashPenTest.Thickness,//1,
            StrokeDashArray = new DoubleCollection() { 8,4 },
            X1 = 0,
            X2 = canvas.Width,
            Y1 = 10,
            Y2 = 10
        }; 
        canvas.Children.Add(testLine);

这个答案利用在 xaml 中生成一个画布:

        <Canvas x:Name ="canvas" Background="White" Height="300" Width="300">

这里的重要方法是“StrokeDashArray”,它生成绘制线条的虚线。更多信息请参见:Shape.StrokeDashArray

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接