Draw an arrow around a line segment. - Java java.awt

Java examples for java.awt:Graphics2D

Description

Draw an arrow around a line segment.

Demo Code


//package com.java2s;

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;

    /**/*from w  w w .j a  v  a 2  s . com*/
     * Draw an arrow around a line segment.
     * @param position the arrow position.
     * @param controlPoint another position that the arrow points away.
     * @param g2 graphic context
     */
    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) {
        // The the angle of the line segment
        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;
    }
}

Related Tutorials