Compute the bounds of a shape when stroked with the given stroke. - Java 2D Graphics

Java examples for 2D Graphics:Shape

Description

Compute the bounds of a shape when stroked with the given stroke.

Demo Code

/*//from w  w w.j  a  v a 2 s . c  o m
 Copyright (c) 1998-2013 The Regents of the University of California
 All rights reserved.
 Permission is hereby granted, without written agreement and without
 license or royalty fees, to use, copy, modify, and distribute this
 software and its documentation for any purpose, provided that the above
 copyright notice and the following two paragraphs appear in all copies
 of this software.

 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
 PROVIDED HEREUNDER IS ON AN  BASIS, AND THE UNIVERSITY OF
 CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 ENHANCEMENTS, OR MODIFICATIONS.

 PT_COPYRIGHT_VERSION_2
 COPYRIGHTENDKEY
 *
 */
//package com.java2s;
import java.awt.BasicStroke;
import java.awt.Shape;
import java.awt.Stroke;

import java.awt.geom.Rectangle2D;

public class Main {
    /** Compute the bounds of a shape when stroked with the given stroke.
     */
    public static Rectangle2D computeStrokedBounds(Shape shape,
            Stroke stroke) {
        if (stroke instanceof BasicStroke) {
            // For some reason (antialiasing?) the bounds returned by
            // BasicStroke is off by one.  This code works around it.
            // if all we want is the bounds, then we don't need to actually
            // stroke the shape.  We've had reports that this is no longer
            // necessary with JDK1.3.
            Rectangle2D rect = shape.getBounds2D();
            int width = (int) ((BasicStroke) stroke).getLineWidth() + 2;
            return new Rectangle2D.Double(rect.getX() - width, rect.getY()
                    - width, rect.getWidth() + width + width,
                    rect.getHeight() + width + width);
        } else {
            // For some reason (antialiasing?) the bounds returned by
            // BasicStroke is off by one.  This code works around it.
            // We've had reports that this is no longer
            // necessary with JDK1.3.
            Rectangle2D rect = stroke.createStrokedShape(shape)
                    .getBounds2D();
            return new Rectangle2D.Double(rect.getX() - 1, rect.getY() - 1,
                    rect.getWidth() + 2, rect.getHeight() + 2);
        }
    }
}

Related Tutorials