【问题标题】:Android textview get line count before draw on canvasAndroid textview在画布上绘制之前获取行数
【发布时间】:2015-05-15 03:21:54
【问题描述】:

我想在绘制文本之前获取行数。在我的代码中,我得到了计数(当前行号)。但它的工作不正确。在 while 循环中,我一步一步设置一个单词,然后尝试比较画布宽度和我的临时文本宽度来了解行数。

    private void draw(Canvas canvas, String text, int size) {
    canvas.drawPaint(paint);

    tv = new TextView(mContext);

    tv.setTextColor(Color.BLACK);

    tv.setTextSize(size);

    int lineHeight = tv.getLineHeight();

    // max lines on the screen
    int lines = canvas.getHeight() / lineHeight;

    //max_height = lines * tv.getLineHeight();

    String screenText = "";

    Pattern stuff = Pattern.compile("[\\w']+|[\\s.,!?;:-]");
    Matcher matcher = stuff.matcher(text);
    List<String> matchList = new ArrayList<String>();

    while (matcher.find()) {
        matchList.add(matcher.group(0));
    }

    // String wholeText[] = text.split(" ");

    int i = 0;
    String word;
    paint.setTextSize(size*3);

    while (count <= lines-1&&i<=matchList.size()-1) {
        word = matchList.get(i++);
        //wholeText[i++];

        screenText += word;
        tempStr += word;

        float w = paint.measureText(tempStr, 0, tempStr.length());

        if(canvas.getWidth() <= w) {
            count++;
            tempStr=word;
        }

        if(count>lines){
            break;
        }

        tv.setText(screenText);

    }

    // you have to enable setDrawingCacheEnabled, or the getDrawingCache will return null
    tv.setDrawingCacheEnabled(true);

    tv.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(canvas.getHeight(), MeasureSpec.EXACTLY));
    tv.setPadding(10,0,10,0);
    //tv.layout(0, 0, tv.getMeasuredWidth(), lines * tv.getLineHeight());
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());

    canvas.drawBitmap(tv.getDrawingCache(), 0, 0, paint);
    //canvas.drawText(tv.getText().toString(), 0, 0, paint);
    // disable drawing cache
    tv.setDrawingCacheEnabled(false);
}

【问题讨论】:

  • @samgak 我用过。但我无法在线获得真实数字。如果没有渲染,我如何获得 textview 宽度?
  • 您没有将tv 添加到任何父视图中,您实际上想要实现什么?
  • @pskink 我想尽可能多地用文本填充屏幕。我想知道我可以在屏幕上设置多少文本(从整个文本中),并且需要知道最后一个单词设置到屏幕上的位置
  • 你为什么不用StaticLayout类?

标签: android canvas textview


【解决方案1】:

写在这里:

fun getTextViewStaticLayout(tv: TextView, width: Int): StaticLayout {
    val textPaint = TextPaint()
    textPaint.isAntiAlias = true
    textPaint.textSize = tv.textSize
    return StaticLayout(tv.text.toString(), textPaint, width, Layout.Alignment.ALIGN_NORMAL,
        1F, 0F, true)
}

width - 与 textView (screenWidth 或其他) 一起使用

那么我们就可以使用staticLayout在draw前获取textView的属性(lineCount, getLineBottom ...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多