在WPF

时间:2017-06-05 10:41:40

标签: c# wpf canvas line stroke

我在我的应用程序中使用System.Windows.Shapes.Line在画布上绘制一条线。我想放一个形状,例如线的起点和终点有一个十字('x')?有没有办法通过设置属性来做到这一点。我可以根据坐标在画布上添加一个'x',但我希望我们可以直接使用一些Line属性来做到这一点。 目前我能够画出这个= --------------- dashed line使用以下代码中的属性: -

var DistanceLine = new Line();
DistanceLine.Stroke = new SolidColorBrush(LineColor);
DistanceLine.StrokeDashArray = new DoubleCollection() {0, 4};
DistanceLine.StrokeDashCap = PenLineCap.Round;
DistanceLine.StrokeEndLineCap = PenLineCap.Round;
DistanceLine.StrokeLineJoin = PenLineJoin.Round;
DistanceLine.StrokeStartLineCap = PenLineCap.Round;
DistanceLine.StrokeThickness = 3;

我想要这样的东西= x ------------------ x dashed line with 'x' marks

如何在线条的末尾制作自定义形状?

1 个答案:

答案 0 :(得分:2)

评论建议并鼓励我写下自己的形状来放置线帽。这可能不是最好的方法,但对我很有帮助。该类将一个对象作为Grid返回,当我绘制一条线时,我可以将其添加到我的画布中。我就是这样做的: -

public class CrossHair : Grid
    {
        public string LineName { get; set; }

        /// <summary>
        /// Draws the crosshair at the given point
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        static public CrossHair DrawCrossHair(double x, double y)
        {
            var crosshair = new CrossHair(); // to contain the cross hair
            var line1 = new Line();
            var line2 = new Line();
            var line3 = new Line();
            var line4 = new Line();
            line1.Stroke = line2.Stroke = line3.Stroke = line4.Stroke = new SolidColorBrush(Colors.Yellow);
            line1.StrokeThickness = line2.StrokeThickness = line3.StrokeThickness = line4.StrokeThickness = 2;

            line1.X1 = x - 5;
            line1.Y1 = y;
            line1.X2 = x - 2;
            line1.Y2 = y;

            line2.X1 = x;
            line2.Y1 = y + 5;
            line2.X2 = x;
            line2.Y2 = y + 2;

            line3.X1 = x + 2;
            line3.Y1 = y;
            line3.X2 = x + 5;
            line3.Y2 = y;

            line4.X1 = x;
            line4.Y1 = y - 2;
            line4.X2 = x;
            line4.Y2 = y - 5;

            crosshair.Children.Add(line1);
            crosshair.Children.Add(line2);
            crosshair.Children.Add(line3);
            crosshair.Children.Add(line4);

            return crosshair;
        }
    }