FontMetrics not correct when run on android device. Simulator fine
Asked Answered
K

1

4

I have an Android App that dynamically scales text depending on the resolution of the android device. I have tested this code on all the predefined resolutions in the Android Simulator and my code works fine. (This includes the same resolutions as on HTC Desire and Motorola Droid)

It also works fine on my HTC Wildfire.

Here are some screen shots from the simulators:

enter image description here enter image description here enter image description here

However... I have tried this on HTC Desire, and I have had reports from users using Motorola Droid that the fonts are not scaling correctly:

enter image description here

Note how it is chopping the text off.

Any ideas why this is not working on these particular devices?

I currently have a function that scales the text down depending on the available height for the text... something like this:

public static float calculateHeight(FontMetrics fm) {

    return Math.abs(fm.ascent) + fm.descent;

}


public static int determineTextSize(Typeface font, float allowableHeight) {

    Paint p = new Paint();
    p.setTypeface(font);

    int size = (int) allowableHeight;
    p.setTextSize(size);

    float currentHeight = calculateHeight(p.getFontMetrics());

    while (size!=0 && (currentHeight) > allowableHeight) {
            p.setTextSize(size--);
        currentHeight = calculateHeight(p.getFontMetrics());
    }

    if (size==0) {
        System.out.print("Using Allowable Height!!");
        return (int) allowableHeight;
    }

    System.out.print("Using size " + size);
    return size;
}

Any ideas why this is happening on only a couple of devices? and how I can fix it? Is there another font metric than I need to be considering here which I don't know about? Like Scale or DPI?

Thanks.

Kiaochow answered 10/3, 2011 at 11:25 Comment(0)
W
6

There are two things I would like to mention.

In my experience I have calculated font height in pixels by subtracting FontMetrics.top from FontMetrics.bottom. This is due to the positive and negative values for bottom and top as per Y axis. Please see android documentation for this. So I would change your calculateHeight method as follows:

public static float calculateHeight(FontMetrics fm) {
    return fm.bottom - fm.top;
}

Secondly you should remember that your determineTextSize method would return the size in pixels. If you are using this to set the Text Size of a TextView or something then you should specify the units as TypedValue.COMPLEX_UNIT_PX. The default unit for this method is TypedValue.COMPLEX_UNIT_SP

Warren answered 20/5, 2011 at 6:34 Comment(1)
Thanks Anupam. I was unaware of the two text size units. Setting the text size with COMPLEX_UNIT_PX, fixes the issues that I was seeing on the HTC Desire and Motorola Droid. Much appreciated.Kiaochow

© 2022 - 2024 — McMap. All rights reserved.