在线算法上绘制箭头

时间:2010-06-09 23:54:39

标签: algorithm drawing line

是否有人在给定线的中间绘制箭头的算法。我搜索了谷歌,但没有找到任何好的实施。

P.S。我真的不介意这种语言,但如果它是Java,它会很棒,因为它是我用的语言。

提前致谢。

2 个答案:

答案 0 :(得分:21)

这是一个绘制箭头的功能,其头部位于p点。您可以将其设置为线的中点。 dx和dy是行方向,由(x1-x0,y1-y0)给出。这将给出一个缩放到行长度的箭头。如果您希望箭头始终具有相同的大小,请将此方向标准化。

private static void DrawArrow(Graphics g, Pen pen, Point p, float dx, float dy)
{
    const double cos = 0.866;
    const double sin = 0.500;
    PointF end1 = new PointF(
        (float)(p.X + (dx * cos + dy * -sin)),
        (float)(p.Y + (dx * sin + dy * cos)));
    PointF end2 = new PointF(
        (float)(p.X + (dx * cos + dy * sin)),
        (float)(p.Y + (dx * -sin + dy * cos)));
    g.DrawLine(pen, p, end1);
    g.DrawLine(pen, p, end2);
}

答案 1 :(得分:12)

这是一种将箭头添加到线条的方法。 你只需要给它箭头和尾部的坐标。

private static void drawArrow(int tipX, int tailX, int tipY, int tailY, Graphics2D g)
{
    int arrowLength = 7; //can be adjusted
    int dx = tipX - tailX;
    int dy = tipY - tailY;

    double theta = Math.atan2(dy, dx);

    double rad = Math.toRadians(35); //35 angle, can be adjusted
    double x = tipX - arrowLength * Math.cos(theta + rad);
    double y = tipY - arrowLength * Math.sin(theta + rad);

    double phi2 = Math.toRadians(-35);//-35 angle, can be adjusted
    double x2 = tipX - arrowLength * Math.cos(theta + phi2);
    double y2 = tipY - arrowLength * Math.sin(theta + phi2);

    int[] arrowYs = new int[3];
    arrowYs[0] = tipY;
    arrowYs[1] = (int) y;
    arrowYs[2] = (int) y2;

    int[] arrowXs = new int[3];
    arrowXs[0] = tipX;
    arrowXs[1] = (int) x;
    arrowXs[2] = (int) x2;

    g.fillPolygon(arrowXs, arrowYs, 3);
}