Figure out width of a String in a certain Font

android, fonts, java, string

Solution

You should be able to use Paint.setTypeface() and then Paint.measureText(). You'll find other methods on the `Paint` class like `setTextSize()` to help too.

Your followup question about scaling text was addressed in this question.

Problem

Is there any way to figure out how many pixels wide a certain `String` in a certain `Font` is? In my `Activity`, there are dynamic `String`s put on a `Button`. Sometimes, the `String` is too long and it's divided on two lines, what makes the `Button` look ugly. However, as I don't use a sort of a console `Font`, the single char-widths may vary. So it's not a help writing something like ``` String test = "someString"; if(someString.length()>/*someValue*/){ // decrement Font size } ``` because an "mmmmmmmm" is wider than "iiiiiiii". Alternatively, is there a way in Android to fit a certain `String` on a single line, so the system "scales" the `Font` size automatically? EDIT: since the answer from wsanville was really nice, here's my code setting the font size dynamically: ``` private void setupButton(){ Button button = new Button(); button.setText(getButtonText()); // getButtonText() is a custom method which returns me a certain String Paint paint = button.getPaint(); float t = 0; if(paint.measureText(button.getText().toString())>323.0){ //323.0 is the max width fitting in the button t = getAppropriateTextSize(button); button.setTextSize(t); } } private float getAppropriateTextSize(Button button){ float textSize = 0; Paint paint = button.getPaint(); textSize = paint.getTextSize(); while(paint.measureText(button.getText().toString())>323.0){ textSize -= 0.25; button.setTextSize(textSize); } return textSize; } ```

Original source

Related problems