java Grapics2D drawString Font Resizing


I'm writing text onto an existing image and I'm using the below to do so.  I've have a requirement to let the text be up to 40 characters on my 200 width image (see dimensions below) and I need to somehow shrink the font based on the text length.  Does FontMetrics support that?  

public class ImageCreator{

public void createImage(String text){
     Graphics2D g = img.getGraphics(); //img is a BufferedImage read in from file system
     [b]Font fnt=new Font("Dante",1,20);
     Color fntC = new Color(4, 4, 109);       
     Dimension d = new Dimension(200, 113);
     drawCenteredString(text, d.width, d.height, g);
public static void drawCenteredString(String s, int w, int h, Graphics g) {
      FontMetrics fm = g.getFontMetrics();
      int x = (w - fm.stringWidth(s)) / 2;
      int y = (fm.getAscent() + (h - (fm.getAscent() + fm.getDescent())) / 2);
      g.drawString(s, x, y);


Open in new window

Who is Participating?
not directly, FontMetric lets you calculate the size of string and you can use that to determine the font size you need to make it fit
I posted an example in one of your previous questions
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

cgray1223Author Commented:
Ok, I think that satisfies one of my use cases where the user enters one long word without any spaces.  I am able to write to the next line of the image but then that opens up another can of worms.  Do you know if anything will support the case when the text is long but has spaces?  For example,
text="This is a test of Font Metrics classsssssssssss"

I'm guessing I'll have to have custom login to break to new lines within the images writable dimension.  
I'd generally use a JTextArea in those case at let it do the wrapping, then use it to 'paint' to the image
I think we already went through the same issue in your orevious question - when
you were fitting the text bewteen some pictures.
It is the samwe thing here - you just try with different
fonts and fontmetrics gives you the size - you rememeber
you decided to break your messaeg  into two lines.

It is all here:
>> and I need to somehow shrink the font based on the text length.  Does FontMetrics support that?  

I already posted an example of exactly that at http:Q_26989670.html#35508813
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.