获取字体缩放因子以计算字体大小

29

这个问题与Android应用程序:如何在设置中读取字体大小?相关。我阅读了CommonsWare的答案,指出要使用Settings.System.FONT_SCALE。所以我写了以下几行代码:

float scale = -66.6f;
try {
    scale = android.provider.Settings.System.getFloat(getContentResolver(),
                                    android.provider.Settings.System.FONT_SCALE);
} catch(SettingNotFoundException e) {
    Log.e(getClass().getSimpleName(), "Error: ", e);
}
Toast.makeText(this, "scale=" + scale, Toast.LENGTH_LONG).show();

我的问题是我在使用一台Android 4.2.2设备时总是遇到SettingNotFoundException。顺便说一句,那段代码位于一个ActivityonCreate回调函数中。

我还通过谷歌搜索了解到大约有三个网站使用相同的代码,是否需要特殊权限?我尝试过使用android.permission.WRITE_SETTINGS权限但没有成功。


嗯,我不确定你是否需要阅读这个。只要使用sp单位,系统不是会自动为您进行缩放吗? - Teovald
当然可以,但我有一些图形 bug 需要通过这个缩放因子来修复。 - rekire
5个回答

60

我在Settings.System的源代码中找到了这个函数:

/** @hide */
public static void getConfigurationForUser(ContentResolver cr,
                                       Configuration outConfig, int userHandle) {
    outConfig.fontScale = Settings.System.getFloatForUser(
        cr, FONT_SCALE, outConfig.fontScale, userHandle);
    if (outConfig.fontScale < 0) {
        outConfig.fontScale = 1;
    }
}

然而,使用了FONT_SCALE,因此我检查了Configuration 类,在该文档中指向 getResources().getConfiguration()。所以我通过使用以下代码解决了问题:

float scale = getResources().getConfiguration().fontScale;

由于我的问题是如何计算正确的像素字体大小,因此这是我现在在Kotlin中使用的方法:

val Number.dpInPx: Int
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP, toFloat(), Resources.getSystem().displayMetrics).toInt()

val Number.spInPx: Int
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, toFloat(), Resources.getSystem().displayMetrics).toInt()

使用方法为:

val textSize = 42.spInPx
val padding = 8.dpInPx

6

您可以根据字体比例设置系统字体。

例如:如果巨大的字体比例为2.0,那么您可以按照以下方式设置。

Configuration config = new Configuration();
config.fontScale = 2.0f;
getResources().getConfiguration().setTo(config);

2
在最后添加“浮点数def”参数
public static float getFloat(ContentResolver cr, String name, float def)

例子:

scale = android.provider.Settings.System.getFloat(getActivity().getContentResolver(),
                                    android.provider.Settings.System.FONT_SCALE, 1f);

0

2023年答案:

这是我使用Kotlin获取fontScale的方法:

val fontScale = resources.configuration.fontScale

技术上没有错,但真正的意图是获取真实的像素尺寸,因此我的dpInPxspInPx Kotlin扩展可能更有帮助。 - rekire

-2

1
这是一个常量数值,在我的设备上始终为 1.33。在发现 FONT_SCALE 之前我曾尝试过这个值。 - rekire
你用的是什么设备?猜测是Nexus 7? - FunkTheMonk
是的,Nexus 7这个问题是众所周知的吗? - rekire
FontScale是用户设置的可用性,与硬件无关。 - Thibault D.

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