0

I am trying to paint a caret at the end of a string but I do not know how to retrieve the dimensions of the given string I am painting with graphics2d.drawString. Or if there is a "shape" that is actually a string with dimensions, that would help to, thanks..

Manny P
  • 33
  • 6
  • http://stackoverflow.com/questions/258486/calculate-the-display-width-of-a-string-in-java – fmgp Aug 21 '13 at 07:18

3 Answers3

1

Something like this:

    Graphics2D g2d = (Graphics2D) g;
    FontRenderContext frc = g2d.getFontRenderContext();
    GlyphVector gv = g2d.getFont().createGlyphVector(frc, "YOUR_STRING");
    Rectangle rect = gv.getPixelBounds(null, INITIAL_X, INITIAL_Y);

    int width = rect.width;
    int height = rect.height;
Ιναη ßαbαηιη
  • 3,410
  • 3
  • 20
  • 41
1

You can try something like this

Graphics2D g2d = ...
Font font = ...
Rectangle2D r = font.getStringBounds("Your_String!", g2d.getFontRenderContext());
System.out.println("(" + r.getWidth() + ", " + r.getHeight() + ")");
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

You can make use of TextLayout for the String drawing. This is very similar to shapes and has much options than plain string drawing.

Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
TextLayout tl = new TextLayout("My String", f, gd2.getFontRenderContext());

// bounds of the TextLayout
Rectangle2D bounds = tl.getBounds();

// draw the text
tl.draw(g2d, x, y)

// position at end
double xEnd = bounds.getWidth() + x;
double yEnd = bounds.getHeight() + y;
Point2D end = new Point2D.Double(bounds.getWidth() + x, bounds.getHeight() + y);
Daniel Lerps
  • 5,256
  • 3
  • 23
  • 33