get Arrow Shape - Java 2D Graphics

Java examples for 2D Graphics:Shape

Description

get Arrow Shape

Demo Code


//package com.java2s;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class Main {
    public static Shape getArrowShape(Line2D line, Point2D intersectionPoint) {
        final double deltaY = line.getP2().getY() - line.getP1().getY();
        final double length = Math.sqrt(Math.pow(deltaY, 2)
                + Math.pow(line.getP2().getX() - line.getP1().getX(), 2));

        double theta = Math.asin(deltaY / length);

        if (line.getP1().getX() > line.getP2().getX()) {
            theta = Math.PI - theta;
        }//from w w  w .  ja  v  a2  s .  c  o  m

        int arrowSize = 9;
        Shape arrowPolygon = new Polygon(new int[] { 0, arrowSize, 0, 0 },
                new int[] { 0, arrowSize / 2, arrowSize, 0 }, 4);
        AffineTransform rotate = AffineTransform.getRotateInstance(theta,
                arrowSize, arrowSize / 2);
        Shape polygon = rotate.createTransformedShape(arrowPolygon);

        AffineTransform move = AffineTransform.getTranslateInstance(
                intersectionPoint.getX() - arrowSize,
                intersectionPoint.getY() - arrowSize / 2);
        polygon = move.createTransformedShape(polygon);
        return polygon;
    }
}

Related Tutorials