如何可靠地确定多线串的宽度?

Mor*_*itz 14 android

我试图计算多行文本段落的宽度.据我所知,唯一可以在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 );
  }
}
Run Code Online (Sandbox Code Playgroud)

Sas*_*Ono 1

您可以尝试使用获取文本边界。

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());
}
Run Code Online (Sandbox Code Playgroud)