Java 怎么在线段周围画一个箭头

2019年8月20日22:29:26 评论 21

1.简介

Java 怎么在线段周围画一个箭头?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import java.awt.Graphics2D;

import java.awt.Point;

import java.awt.geom.GeneralPath;

public class Main {
    public static final int ARROW_LENGTH = 8;
    public static final double ARROW_ANGLE = Math.PI / 6;

    
     
    public static void drawArrow(Point position, Point controlPoint,
            Graphics2D g2) {
        GeneralPath path = createArrowPath(position, controlPoint);
        g2.draw(path);
        g2.fill(path);
    }

    private static GeneralPath createArrowPath(Point position,
            Point controlPoint) {
        
        double alpha = Math.atan((double) (position.y - controlPoint.y)
                / (position.x - controlPoint.x));
        if (controlPoint.x > position.x)
            alpha += Math.PI;
        double angle = ARROW_ANGLE - alpha;
        GeneralPath path = new GeneralPath();
        float x1 = (float) (position.x - ARROW_LENGTH * Math.cos(angle));
        float y1 = (float) (position.y + ARROW_LENGTH * Math.sin(angle));
        path.moveTo(x1, y1);
        path.lineTo(position.x, position.y);
        angle = ARROW_ANGLE + alpha;
        float x2 = (float) (position.x - ARROW_LENGTH * Math.cos(angle));
        float y2 = (float) (position.y - ARROW_LENGTH * Math.sin(angle));
        path.lineTo(x2, y2);
        path.closePath();
        return path;
    }
}

 

3.总结

示例代码演示了 Java 怎么在线段周围画一个箭头,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: