Question

I have a textview of width maxWidth. I am using following function to choose font size of a string to fit in the textview. The function returns fontsize such that the width of the string matches the textview width. However the textview shows only part of the string . What is wrong ?

private int determineMaxTextSize(String str, float maxWidth)
{
    int size = 0;       
    Paint paint = new Paint();

    do {
        paint.setTextSize(++ size);
    } while(paint.measureText(str) < maxWidth);



    Log.d("wop",""+paint.measureText(str));
    return size;
}

This is how the string is displayed.

LayoutParams params;
params = textview.getLayoutParams();
params.height = maxWidth;
params.width=maxWidth;
textview.setLayoutParams(params);
int textsize=determineMaxTextSize("60 s", maxWidth);
textview.setTextSize(textsize);
textview.setText("60 s");

This is the outcome.

enter image description here

Was it helpful?

Solution

Paint#measureText() returns value in dip. Need to convert it to pixels.

Try this code:

private int determineMaxTextSize(String str, float maxWidth) {
    int size = 0;
    Paint paint = new Paint();

    float scaleDensity = getResources().getDisplayMetrics().density;

    do {
        paint.setTextSize(++ size);
    } while (paint.measureText(str) * scaleDensity < maxWidth);

    return --size;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top