Passing a certain height 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 height 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 {
    /**//  www .  j a v  a 2 s.  c o  m
     * Passing a certain height 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 height    The given width to find the text size
     * @return text size value in accordance to height
     */
    public static float findTextSizeByHeight(String text, float height) {
        Paint paint = new Paint();
        Rect bounds = new Rect();
        float toReturn = 0.5f;

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

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

Related Tutorials