简体   繁体   中英

Java: How to dynamically fit painted text into window

im trying to paint a big "hello world" on my frame/component. But i want to dynamically fit it to the window size. So everytime i resize the window the text should perfectly fit into the window.

I use the FontMetrics class to which i assign a font and the measure the widht and height of a character.

But it would be good to have a method i pass the size of a component with a text and the method returns a font i need to use. Well, a font size for a specific font would be enough.

Something like this:

public int getFontSizeForDrawArea( int width, int height, String text, Font font) {
  //Pseudo class FontMeasureClass takes a font to do the measures with
  FontMeasureClass measure = new FontMeasureClass( font);

  // method takes size of frame/component and text to return the needed 
  // font size to fit text to frame/component
  return measure.getFontSize( width, height, text);
}

I think about making a method which measures the size of a text by trying in a loop until the size is as close as much to the windows widht and height. But maybe there is something ready to use.

One way of measuring the width of your String in pixels is this one:

Font myfont = jTextField1.getFont();      
FontMetrics myMetrics = getFontMetrics(myfont);
int width=SwingUtilities.computeStringWidth(myMetrics, jTextField1.getText()); 

and here is another one, that calculates additionally it's height in pixels as well:

Font myFont = new Font("Arial", Font.PLAIN, 10);
FontMetrics myMetrics = new FontMetrics(myFont) {};
Rectangle2D boundsOfString = myMetrics.getStringBounds("Measure this String", null);
int width = (int) boundsOfString.getWidth();
int height = (int) boundsOfString.getHeight();

I would do it with the loop you mentioned above.

You could calculate the width and paint your text in a big font and resize it down with Graphics2D.scale . Usually, the paintComponent-Method receives a Graphics2D object, so you can cast the Graphics object you got into Graphics2D.

You don't have to use a loop, but can estimate an appropriate font size after one miscalculation, as most fonts scale proportionally (although fonts may contain different glyphs for different sizes).

Eg if your painting area is 1000px wide and the computed width for a 100pt font size is 1250px, then a font size of 100pt*1000px/1250px = 80pt should result in a width of 1000px.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM