Expand or shrink a shape in all directions by a defined offset. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Expand or shrink a shape in all directions by a defined offset.

Demo Code


import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.FlatteningPathIterator;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Main{
    /**//w  w w.j a v a2s. c  o m
     * Precision.
     */
    public static final double EPSILON = 1e-5;
    /**
     * Expand or shrink a shape in all directions by a defined offset.
     *
     * @param s      Shape
     * @param offset Offset
     * @return New shape that was expanded or shrunk by the specified amount
     */
    public static Area grow(final Shape s, final double offset) {
        return grow(s, offset, BasicStroke.JOIN_MITER, 10f);
    }
    /**
     * Expand or shrink a shape in all directions by a defined offset.
     *
     * @param s          Shape
     * @param offset     Offset to expand/shrink
     * @param join       Method for handling edges (see BasicStroke)
     * @param miterlimit Limit for miter joining method
     * @return New shape that is expanded or shrunk by the specified amount
     */
    public static Area grow(final Shape s, final double offset, int join,
            float miterlimit) {
        Area shape = new Area(s);

        if (MathUtils.almostEqual(offset, 0.0, EPSILON)) {
            return shape;
        }

        Stroke stroke = new BasicStroke((float) Math.abs(2.0 * offset),
                BasicStroke.CAP_SQUARE, join, miterlimit);
        Area strokeShape = new Area(stroke.createStrokedShape(s));

        if (offset > 0.0) {
            shape.add(strokeShape);
        } else {
            shape.subtract(strokeShape);
        }

        return shape;
    }
}

Related Tutorials