I\'m trying to write application which need to draw many strings using Graphics2D
class in Java. I need to get sizes of each String object (to calculate exact p
Here is a snippet of code that does something similar -- wrote it for abbreviating the string to a given number of pixels.
public static String abbreviate(final Graphics2D g2, final String text, final int fitToWidth) {
// define how many characters in the caption can be drawn
final FontMetrics fm = g2.getFontMetrics();
Rectangle2D textBounds = fm.getStringBounds(text, g2);
int count = text.length();
while ((textBounds.getWidth() > fitToWidth) && (count > 4)) {
textBounds = fm.getStringBounds(text.substring(0, count--), g2);
}
return count == text.length() ? text : StringUtils.abbreviate(text, count);
}