set Text Size For Width in Canvas - Android Graphics

Android examples for Graphics:Canvas

Description

set Text Size For Width in Canvas

Demo Code


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

public class Main {
    public static float setTextSizeForWidth(Paint paint,
            float desiredWidth, String text, float max, float min) {
        final float textSize = 12.0f;

        paint.setTextSize(textSize);/*from   w  w w.  j  ava2  s  .  c o  m*/
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        float desiredTextSize = textSize * desiredWidth / bounds.width();
        if (desiredTextSize > max) {
            desiredTextSize = max;
        } else if (desiredTextSize < min) {
            desiredTextSize = min;
        }
        paint.setTextSize(desiredTextSize);
        return desiredTextSize;
    }

    private static float setTextSizeForWidth(Paint paint,
            float desiredWidth, String text, float max) {
        return setTextSizeForWidth(paint, desiredWidth, text, max, 0.0f);
    }

    public static float setTextSizeForWidth(Paint paint,
            float desiredWidth, String text) {
        return setTextSizeForWidth(paint, desiredWidth, text,
                Float.MAX_VALUE, 0.0f);
    }
}

Related Tutorials