【问题标题】:How to make Paint.breakText respect word wrapping?如何使 Paint.breakText 尊重自动换行?
【发布时间】:2019-11-18 13:37:50
【问题描述】:

我想计算一些文本需要多少行才能放入固定宽度的TextView。我为此使用了Paint.breakText

int maxWidth = WIDTH_IN_PIXELS;
int index = 0;
int linecnt = 0;
while (true) {
    float[] measuredWidth = new float[1];
    int advances = labelView.getPaint().breakText(text, index, text.length(), true,  maxWidth, measuredWidth);
    linecnt += 1;
    index += advances;
    if(index>=desc.length()) break;           
}

但是,计算出的linecnt 总是比实际需要的少一。经过进一步调查,我发现 API 在单词中的任意点中断文本,但是当 TextView 布局文本时,它永远不会中断一个单词:

// textBreak:
Hello Wo
rld
// Real layout:
Hello
World

如何让 breakText 尊重自动换行?或者有没有其他方法可以做到这一点?

附言我知道我总是可以回到循环中单词的开头,但这看起来很老套,并不适用于每种语言。我确信 Android 有一些优雅的方法可以做到这一点,但我不知道要使用的 API/Flag。

p.p.s 有时 TextView 使用破折号 (-) 将长单词换行,其规则不清楚。

【问题讨论】:

    标签: android textview word-wrap android-paint


    【解决方案1】:

    这感觉有点hacky,它不会在中间用破折号自动断字,但我的想法是我有一串断字字符,然后向后迭代直到我碰到一个断字符。如果单词超长且没有换行符,则在行尾换行即可。

    var wordCharsToFit = labelView.getPaint().breakText(text, index, text.length(), true,  maxWidth, measuredWidth);
    while (wordCharsToFit > 0 && (
                lyrics.length > wordCharsToFit && !"‐–〜゠= \t\r\n".contains(lyrics[wordCharsToFit]) ||
                chords.length > wordCharsToFit && !"‐–〜゠= \t\r\n".contains(chords[wordCharsToFit])
    )) {
        wordCharsToFit -= 1
    
        if (wordCharsToFit == 0) {
            wordCharsToFit = totalCharsToFit
            break
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 1970-01-01
      • 2018-04-02
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多