gpt4 book ai didi

java - 在 Android 设备上运行时 FontMetrics 不正确。模拟器很好

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:38 24 4
gpt4 key购买 nike

我有一个 Android 应用程序,可以根据 Android 设备的分辨率动态缩放文本。我已经在 Android 模拟器中的所有预定义分辨率上测试了这段代码,我的代码工作正常。 (这包括与 HTC Desire 和 Motorola Droid 相同的分辨率)

它在我的 HTC Wildfire 上也能正常工作。

以下是模拟器的一些屏幕截图:

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

但是...我已经在 HTC Desire 上试过了,并且我收到了来自使用 Motorola Droid 的用户的报告,字体没有正确缩放:

enter image description here

注意它是如何截断文本的。

知道为什么这不适用于这些特定设备吗?

我目前有一个功能,可以根据文本的可用高度缩小文本...像这样:

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?

谢谢。

最佳答案

有两件事我想提一下。

根据我的经验,我通过从 FontMetrics.bottom 中减去 FontMetrics.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

关于java - 在 Android 设备上运行时 FontMetrics 不正确。模拟器很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com