开发者

Java: How to dynamically fit painted text into window

开发者 https://www.devze.com 2023-02-03 20:25 出处:网络
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.

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.


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.


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 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).

E.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消