gpt4 book ai didi

android - LineSpace 如何影响一行文本中的 StaticLayout 高度

转载 作者:搜寻专家 更新时间:2023-11-01 08:29:58 24 4
gpt4 key购买 nike

考虑这个简单的例子:

我有这样的单行文本:“你好”

我想使用 StaticLayout 测量此文本。所以我写了这样的东西:

StaticLayout layout = new StaticLayout("Hello", myTextView.getPaint(), myTextView.getWidth(), Layout.Alignment.NORMAL, 1, lineSpace, false);

在上面的代码中,我在 for 循环中更改了 lineSpace 变量,并且每次都记录布局的高度:

for(int lineSpace=0; lineSpace<20;lineSpace++){
StaticLayout layout = new StaticLayout("Hello", myTextView.getPaint(), myTextView.getWidth(), Layout.Alignment.NORMAL, 1, lineSpace, false);

Log.d("TAG", "layout height: " + layout.getHeight());
}

当我在带有 android M 布局的设备上运行此代码时,高度不会随着 lineSpace 的多个值而改变。但在较低的 android 版本中,布局的高度分别随行间距而变化。

虽然当你的文本超过一行时,StaticLayout 会考虑两行之间的行间距。但似乎 Android M 不考虑最后一行的行空间,但较低的 Android 版本会考虑。

我的问题是:在什么版本的 android StaticLayout 之后考虑最后一行的行空间?我可以这样写吗:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// in this version StaticLayout don't consider line space for last line
} else {
// in this version StaticLayout consider line space for last line
}

最佳答案

我在源代码中做了一些快速挖掘,似乎是 this part是罪魁祸首:

    if (needMultiply && !lastLine) {
double ex = (below - above) * (spacingmult - 1) + spacingadd;
if (ex >= 0) {
extra = (int)(ex + EXTRA_ROUNDING);
} else {
extra = -(int)(-ex + EXTRA_ROUNDING);
}
} else {
extra = 0;
}

旧版本缺少 !lastLine 条件,因此也会在最后一行添加间距。

条件是在this commit中添加的,如果我的 github foo 没有让我失望,应该从 Android 5 开始包含它。

显然,就像提交提到的那样,这只影响单行文本,对于多行文本,高度似乎计算正确。因此,一个简单的解决方法可能是检查文本是否只有一行(使用 getLineCount())以及 Android 版本是否小于 5,如果小于 5,则减去一次行距。

关于android - LineSpace 如何影响一行文本中的 StaticLayout 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719899/

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