在线算法上绘制箭头

nun*_*nos 14 algorithm drawing line

有没有人有一个算法在给定的行中间绘制箭头.我搜索过谷歌,但没有找到任何好的实施.

PS我真的不介意语言,但如果它是Java,它会很棒,因为它是我正在使用的语言.

提前致谢.

bbu*_*dge 21

这是一个用箭头绘制箭头的函数.您可以将其设置为线的中点.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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如何调整箭头的大小?我喜欢根据线条的长度来确定它,但箭头大小与线条大小的当前比率对于我的应用来说是不正确的. (2认同)

Kom*_*lot 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);
}
Run Code Online (Sandbox Code Playgroud)