Skip to content

Instantly share code, notes, and snippets.

@johnmay
Created October 30, 2012 16:52
Show Gist options
  • Save johnmay/3981487 to your computer and use it in GitHub Desktop.
Save johnmay/3981487 to your computer and use it in GitHub Desktop.
getTextBounds(String, double, double, Graphics2D)
public Rectangle2D getTextBounds(String text, double x, double y,
Graphics2D graphics) {
FontMetrics fontMetrics = graphics.getFontMetrics();
Rectangle2D bounds = fontMetrics.getStringBounds(text, graphics);
double widthPad = 3;
double heightPad = 1;
double width = bounds.getWidth() + widthPad;
double height = bounds.getHeight() + heightPad;
// centre the rectangle on the given x and y
return new Rectangle2D.Double(x - width / 2, y - height / 2,
width, height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment