如何在WPF程序中以编程方式绘制箭头?

3

我需要在WPF程序中以编程方式绘制箭头。我记得Windows Forms有原始图形绘制箭头,可以设置PenCap

mMyPen.CustomEndCap =
    new AdjustableArrowCap(arrowSize, arrowSize, true);

WPF是否可行?
2个回答

4

是的,我已经找到这个库了,但我不知道如何自定义箭头破折号样式,例如点-点或短划线-点... - Daniel Peñalba
@DanielPeñalba - 你尝试过ArrowLine的StrokeDashArray属性吗?例如:myArrow.StrokeDashArray = new DoubleCollection() { 1, 1 }; 或者 ... new DoubleCollection() { 3, 2, 1, 2 }。查看此答案以获取更多StrokeDash示例:在WPF中绘制线条和圆形 - Sphinxxx

2
我已经创建了下面的方法,用于创建带箭头的线段的PointCollection:
private const double _maxArrowLengthPercent = 0.3; // factor that determines how the arrow is shortened for very short lines
private const double _lineArrowLengthFactor = 3.73205081; // 15 degrees arrow:  = 1 / Math.Tan(15 * Math.PI / 180); 

public static PointCollection CreateLineWithArrowPointCollection(Point startPoint, Point endPoint, double lineWidth)
{
    Vector direction = endPoint - startPoint;

    Vector normalizedDirection = direction;
    normalizedDirection.Normalize();

    Vector normalizedlineWidenVector = new Vector(-normalizedDirection.Y, normalizedDirection.X); // Rotate by 90 degrees
    Vector lineWidenVector = normalizedlineWidenVector * lineWidth * 0.5;

    double lineLength = direction.Length;

    double defaultArrowLength = lineWidth * _lineArrowLengthFactor;

    // Prepare usedArrowLength
    // if the length is bigger than 1/3 (_maxArrowLengthPercent) of the line length adjust the arrow length to 1/3 of line length

    double usedArrowLength;
    if (lineLength * _maxArrowLengthPercent < defaultArrowLength)
        usedArrowLength = lineLength * _maxArrowLengthPercent;
    else
        usedArrowLength = defaultArrowLength;

    // Adjust arrow thickness for very thick lines
    double arrowWidthFactor;
    if (lineWidth <= 1.5)
        arrowWidthFactor = 3;
    else if (lineWidth <= 2.66)
        arrowWidthFactor = 4;
    else
        arrowWidthFactor = 1.5 * lineWidth;

    Vector arrowWidthVector = normalizedlineWidenVector * arrowWidthFactor;


    // Now we have all the vectors so we can create the arrow shape positions
    var pointCollection = new PointCollection(7);

    Point endArrowCenterPosition = endPoint - (normalizedDirection * usedArrowLength);

    pointCollection.Add(endPoint); // Start with tip of the arrow
    pointCollection.Add(endArrowCenterPosition + arrowWidthVector);
    pointCollection.Add(endArrowCenterPosition + lineWidenVector);
    pointCollection.Add(startPoint + lineWidenVector);
    pointCollection.Add(startPoint - lineWidenVector);
    pointCollection.Add(endArrowCenterPosition - lineWidenVector);
    pointCollection.Add(endArrowCenterPosition - arrowWidthVector);

    return pointCollection;
}

你可以使用以下代码轻松创建线条形状:
var points = CreateLineWithArrowPointCollection(new Point(0, 0), new Point(200, 100), 5);

var polygon = new Polygon();
polygon.Points = points;
polygon.Fill = Brushes.Red;

RootCanvas.Children.Add(polygon);

该代码还支持缩短短线的箭头。

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