determining a strings length in pixels

Is it possible to find the width of a string drawn onto an applet or canvas? Ive estimated the height to be roughly ten pixels (hey maybe thats why its considered font 10?). Howeve, is there some way of calculating the length? I would like to do this because i am trying to draw various "cards" on a canvas, and would like to be able to center the card's name as well as a certain number pertaining to that card on the RoundRect ive already drawn. Any suggestions?

Comments


  • here's the elements for one way of getting the font size.

    Font font; // the font you are measuring
    String text= "some String" ; // a string 0-any number of chars.
    Graphics g; // the object passed to paint or Component.getGraphics();
    Graphics2D g2 = (Graphics2D)g;
    FontRenderContext context= g2.getFontRenderContext(); //
    Rectangle2D rect = getStringBounds(text, context);
    rect won't know the position of the font, but holds the dimension reliably.

    A similar, but simpler way is through the FontMetrics class.
    Since it's simpler and similar, I'll leave it to you to peruse the api.
    The FontMetrics class, as it's name suggests serves to measure fonts.

    ~S~



    : Is it possible to find the width of a string drawn onto an applet or canvas? Ive estimated the height to be roughly ten pixels (hey maybe thats why its considered font 10?). Howeve, is there some way of calculating the length? I would like to do this because i am trying to draw various "cards" on a canvas, and would like to be able to center the card's name as well as a certain number pertaining to that card on the RoundRect ive already drawn. Any suggestions?
    :

  • thx. actually i found a post on a sun board that recommended fontMetrics before i got this response so i ended up using that. but ill keep this method in mind to
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories