在安卓设备上运行时,字体度量不正确。模拟器正常。

4
我有一个Android应用程序,根据android设备的分辨率动态缩放文本。我已经在Android模拟器中测试了这段代码,并且我的代码可以正常工作(包括与HTC Desire和Motorola Droid相同的分辨率)。它也可以在我的HTC Wildfire上正常工作。以下是一些来自模拟器的屏幕截图:
但是...我已经尝试在HTC Desire上使用它,并且有用户使用Motorola Droid报告说字体未正确缩放:
请注意,它正在截断文本。
这个问题出现在这些特定的设备上有什么想法吗?我目前有一个函数,根据文本的可用高度缩小文本...类似于这样:
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;
}

有什么想法,为什么只有几个设备会出现这种情况?我该怎么解决? 还有其他字体度量标准需要考虑吗?比如比例或DPI? 谢谢。
1个回答

6

我想提及两件事情。

根据我的经验,我通过将FontMetrics.top减去FontMetrics.bottom来计算像素中的字体高度。这是由于bottom和top相对于Y轴具有正负值。请参考android文档。因此,我会将你的calculateHeight方法更改如下:

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

其次,您需要记住,您的determineTextSize方法将以像素为单位返回大小。如果您使用它来设置TextView或其他内容的文本大小,则应将单位指定为TypedValue.COMPLEX_UNIT_PX。此方法的默认单位是TypedValue.COMPLEX_UNIT_SP。


感谢Anupam。 我不知道有两个文本大小单位。 使用COMPLEX_UNIT_PX设置文本大小可以解决我在HTC Desire和Motorola Droid上遇到的问题。非常感谢。 - Sprooose

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接