我正在计算多行文本段落的宽度。据我所知,在android中唯一能做到这一点的类是staticlayout(或dynamiclayout)类。当使用这个类时,我没有得到适当长度的文本片段,而是测量的维度有时更小,有时更大,这取决于文本大小。
所以我基本上是在寻找一种可靠的方法来测量多行文本字符串的宽度。
下图显示了不同文本大小下测量的宽度与实际文本长度的差异。
屏幕截图是在自定义视图中运行以下代码创建的:

@Override
protected void onDraw( Canvas canvas ) {
  for( int i = 0; i < 15; i++ ) {
    int startSize = 10;
    int curSize = i + startSize;
    paint.setTextSize( curSize );
    String text = i + startSize + " - " + TEXT_SNIPPET;
    layout = new StaticLayout( text,
                               paint,
                               Integer.MAX_VALUE,
                               Alignment.ALIGN_NORMAL,
                               1.0f,
                               0.0f,
                               true );

    float top = STEP_DISTANCE * i;
    float measuredWidth = layout.getLineMax( 0 );
    canvas.drawRect( 0, top, measuredWidth, top + curSize, bgPaint );
    canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
  }
}

最佳答案

您可以尝试使用get text bounds。

private int calculateWidthFromFontSize(String testString, int currentSize)
{
    Rect bounds = new Rect();
    Paint paint = new Paint();
    paint.setTextSize(currentSize);
    paint.getTextBounds(testString, 0, testString.length(), bounds);

    return (int) Math.ceil( bounds.width());
}

private int calculateHeightFromFontSize(String testString, int currentSize)
{
    Rect bounds = new Rect();
    Paint paint = new Paint();
    paint.setTextSize(currentSize);
    paint.getTextBounds(testString, 0, testString.length(), bounds);

    return (int) Math.ceil( bounds.height());
}

08-18 16:42
查看更多