Passing a certain width value, this method returns the size of text of which it is the size of the width specified - Android Graphics

Android examples for Graphics:Paint

Description

Passing a certain width value, this method returns the size of text of which it is the size of the width specified

Demo Code


//package com.java2s;
import android.graphics.Paint;
import android.graphics.Rect;

public class Main {
    /**/*from  w  w w  .ja  v  a 2  s .  c om*/
     * Passing a certain width value, this method returns the size of text of which it is the size of the width specified
     * @param text     Text to calculate text size by
     * @param width    The given width to find the text size
     * @return text size value in accordance to width
     */
    public static float findTextSizeByWidth(String text, float width) {
        Paint paint = new Paint();
        Rect bounds = new Rect();
        float toReturn = 0.5f;

        paint.setTextSize(toReturn);
        paint.getTextBounds(text, 0, text.length(), bounds);

        while (bounds.width() < width) {
            toReturn += 0.5f;
            paint.setTextSize(toReturn);
            paint.getTextBounds(text, 0, text.length(), bounds);
        }
        return toReturn;
    }
}

Related Tutorials