【问题标题】:Android Paint breakText new lineAndroid Paint breakText 换行
【发布时间】:2016-10-02 22:41:53
【问题描述】:

我使用Paint.breakText() 来获取行数。但它似乎不适用于'\n'。

text = "a\n";
int lineCount = 0;
int index = 0;
int length = text.length();
//maxWidthPX is 240
while(index < length - 1) {
    index += paint.breakText(text, index, length, true, maxWidthPX, null);
    lineCount++;
}

应该 lineCount 是 2。 但事实证明 lineCount 是 1。 不应该是2吗?原因文本包含换行符:'\n'。

AndroidStudio debug break

【问题讨论】:

  • 你的长度是 2。你正在循环直到长度低于 -1(所以 1)。你只会进入一次循环,因此增加 lineCount 一次。

标签: java android newline paint


【解决方案1】:

根据官方文档paint.breakText()需要如下参数:

public int breakText(CharSequence text, int start, int end, boolean measureForwards, float maxWidth, float[] measuredWidth) 

所以,它打破了你写的从开始到结束位置的字符序列:

paint.breakText(text, index, length, true, maxWidthPX, null);

哪里,end = 长度

这就是为什么,它总是执行一次!

我已经编辑了你的代码:

text = "a\n";
int lineCount = 0;
int index = 0;
int length = text.length();
//maxWidthPX is 240
while(index <= length - 1) {
    index += paint.breakText(text, index, index + 1, true, maxWidthPX, null);
    lineCount++;
}

而且,发现 lineCount 是 2。

【讨论】:

    【解决方案2】:

    最后,我找到了使用 String split() 的解决方案

            String[] textStr = text.split("\\n");
        int allLineCount = 0;
        for (String textTmp : textStr) {
            int lineCount = 0;
            int index = 0;
            int length = textTmp.length();
    
            while (index < length - 1) {
                index += paint.breakText(textTmp, index, length, true, maxWidthPX, null);
                lineCount++;
            }
            allLineCount += lineCount;
        }
    

    【讨论】:

      猜你喜欢
      • 2012-05-16
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      相关资源
      最近更新 更多