Java: how to dynamically fit colored text into a window

im trying to paint a big "hello world" on my frame / component. But I want to dynamically fit it to the size of the window. Therefore, every time I change the size of the window, the text should fit perfectly into the window.

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

But it would be nice to have a way to pass the size of the component with the text, and the method returns the font that I need to use. Well, the font size for a particular font will be enough.

Something like that:

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 am thinking of creating a method that measures the size of text, trying in a loop until the size is so close to the width and height of the window. But perhaps there is something ready to use.

+4
source share
3 answers

One way to measure the width of your string in pixels:

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

and here is another one that additionally calculates the height in pixels:

 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 this with the loop mentioned above.

+2
source

You can calculate the width and draw the text in large font and resize it to Graphics2D.scale . Typically, the paintComponent method gets a Graphics2D object, so you can use the Graphics object you got in Graphics2D.

+2
source

You do not need to use a loop, but you can estimate the corresponding font size after one calculation, as most fonts are scaled proportionally (although fonts can contain different glyphs for different sizes).

eg. if your drawing area has a width of 1000 pixels and the calculated width for a font size of 100pt is 1250 pixels, the font size of 100pt * 1000px / 1250px = 80pt should have a width of 1000 pixels.

0
source

Source: https://habr.com/ru/post/1335083/


All Articles