Adjusts the Paint text size for the given parameters. - Android Graphics

Android examples for Graphics:Paint

Description

Adjusts the Paint text size for the given parameters.

Demo Code


//package com.java2s;

import android.graphics.Paint;
import android.graphics.Rect;

public class Main {
    /**//from   www  .  ja va 2s .  c o m
     * Adjusts the text size for the given parameters. Called from adjustTextSize().
     *
     * @param text
     * @param textPaint
     * @param height
     */
    public static void adjustTextSizeForHeight(String text,
            Paint textPaint, int height) {
        textPaint.setTextSize(100);
        textPaint.setTextScaleX(1.0f);
        Rect bounds = new Rect();
        // ask the paint for the bounding rect if it were to draw this text
        textPaint.getTextBounds(text, 0, text.length(), bounds);

        // get the height that would have been produced
        int h = bounds.bottom - bounds.top;

        // make the text text up 100% of the height
        float target = (float) height * 1.0f;

        // figure out what textSize setting would create that height of text
        float size = ((target / h) * 100f);

        // and set it into the paint
        textPaint.setTextSize(size);
    }
}

Related Tutorials