winforms 如何在物体上画一条虚线?

vd2z7a6w  于 2023-02-19  发布在  其他
关注(0)|答案(6)|浏览(194)

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

我想知道是否有可能画一条虚(点)线来代替普通的实线?

acruukt9

acruukt91#

这是非常简单的,一旦你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数组中的数字代表不同颜色的短划线长度。因此,对于一个简单的长划线,每个短划线上有2个像素(黑色),每个短划线上有2个像素,你的数组看起来像这样:{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);
5uzkadbs

5uzkadbs2#

我想你可以通过改变你画线的笔来完成这个任务。所以,把你例子中的最后两行替换成:

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

p4tfgftt3#

Pen具有定义为的公共属性

public DashStyle DashStyle { get; set; }

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

7fhtutme

7fhtutme5#

在更现代的C#中:

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

qjp7pelc6#

要回答有关使用代码隐藏生成虚线的问题:

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

相关问题