How LineSpace Affects StaticLayout Height in One Line Text

我是研究僧i 提交于 2020-01-04 09:17:55

问题


Consider this simple example:

I have a single line text like this: "Hello"

I wanna measure this text using StaticLayout. So I wrote something like this:

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

In above code I changed lineSpace variable in a for loop and every time log the layout's height:

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());
}

When I run this code on device with android M layout't height doesn't changed with multiple values of lineSpace. But in lower android versions layout's height changed with line space respectively.

Although when your text is more than one line ,StaticLayout consider line space between two lines. But it seems Android M doesn't consider line space for last line but lower Android versions does.

My question is this: After what version of android StaticLayout consider line space for last line? Can I wrote something like this:

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
}

回答1:


I did some quick digging in the source code, seems to be that this part is the culprit:

    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;
    }

Older versions are missing the !lastLine condition and thus also add the spacing to the last line.

The condition was added in this commit, which, if my github foo doesn't fail me, should be included starting with Android 5.

Apparently, just like the commit mentions, this only affects single line texts, for multiline texts the height seems to be calculated correctly. So an easy fix might be to check whether the text only has a single line (using getLineCount()) and if the Android version is less than 5, and if so substract the line spacing once.



来源:https://stackoverflow.com/questions/41719899/how-linespace-affects-staticlayout-height-in-one-line-text

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