Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate text size according to width of text area

I have a text that should be set to TextView with specified width. It needs to calculate the text size to fit it into TextView.

In other words: Is there a way to fit text into TextView area, like the ImageView scale type feature?

like image 433
kankan Avatar asked Jan 25 '11 14:01

kankan


People also ask

How do you calculate font size?

A font is often measured in pt (points). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch.

How do you get the height of the text inside of a textarea?

You should have the following code somewhere at the beginning of the document. // set one row in the textarea and get its height element. rows = 1; var height1 = parseFloat(window. getComputedStyle(element)["height"]); // set two rows in the textarea and get its height element.

How do you scale text in HTML?

In HTML, you can change the size of text with the <font> tag using the size attribute. The size attribute specifies how large a font will be displayed in either relative or absolute terms. Close the <font> tag with </font> to return to a normal text size.

How do I automatically adjust font size in CSS?

The font-size-adjust property of CSS tells the browser to adjust the font size of the text to the same size regardless of font family. When the first chosen font is not available, the font-size-adjust property allows you more control over the font size.


1 Answers

This should be a simple solution:

public void correctWidth(TextView textView, int desiredWidth) {     Paint paint = new Paint();     Rect bounds = new Rect();      paint.setTypeface(textView.getTypeface());     float textSize = textView.getTextSize();     paint.setTextSize(textSize);     String text = textView.getText().toString();     paint.getTextBounds(text, 0, text.length(), bounds);      while (bounds.width() > desiredWidth)     {         textSize--;         paint.setTextSize(textSize);         paint.getTextBounds(text, 0, text.length(), bounds);     }      textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); } 
like image 140
Hamzeh Soboh Avatar answered Sep 19 '22 01:09

Hamzeh Soboh