FontMetrics not correct when run on android device. Simulator fine

岁酱吖の 提交于 2019-12-23 12:56:23

问题


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:

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:

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.


回答1:


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



来源:https://stackoverflow.com/questions/5259015/fontmetrics-not-correct-when-run-on-android-device-simulator-fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!