Search code examples
javaswinggraphicsawtjava-2d

How to compute a path bounding box taking into account the Stroke


I am currently drawing a line using the code below and would like to get the bounding box around my path but if I call path.getBounds() I get a bounding box that ignore the stroke width and line join thus my drawing end-up having some part clipped when place inside a JViewport. How can I get the bounding box of what will really get drawn.

The only thing I found is the following class but the source is not available http://pic.dhe.ibm.com/infocenter/jviewtgo/v8r8/index.jsp?topic=%2Fcom.ibm.ilog.jviews.tgo.doc%2Fhtml%2Frefjava%2Fhtml%2Filog%2Ftgo%2Fgrprim%2Fpackage-summary.html

GeneralPath  path = new GeneralPath();
if (fPoints.size() > 0) {
    Point first = (Point)fPoints.elementAt(0);
    path.moveTo((float)first.getX(),(float) first.getY());
     for (int i = 1; i < fPoints.size(); i++) {
        Point p1 = (Point) fPoints.elementAt(i);
        path.lineTo(p1.x, p1.y);
    }
}
g2d.setStroke(new BasicStroke(lineModel.getStrokeWidth(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
g2d.setColor(lineModel.getLineColor());
g2d.draw(path);

Solution

  • I finally found the solution is to use the stroke object itself

    Stroke s = new BasicStroke(lineModel.getStrokeWidth(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);
    s.createStrokedShape(path).getBounds();