如何可靠地确定多行字符串的宽度? [英] How to reliably determine the width of a multi line string?

查看:125
本文介绍了如何可靠地确定多行字符串的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算出多行文本段的宽度。据我所知,这是Android做到这一点的唯一类是StaticLayout(或DynamicLayout)类。当使用这个类我都没有得到适当的长度我的文字片断,而是被测尺寸有时小,有时甚至更大的取决于文字的大小。

,所以我基本上寻找一种方式来可靠地测量多行文本字符串的宽度。

下图显示了测量宽度发散从各种文本尺寸的实际文本长度。

该屏幕快照创建运行在自定义视图中使用code:

  @覆盖
保护无效的OnDraw(帆布油画){
  的for(int i = 0; I< 15;我++){
    INT startSize = 10;
    INT curSize = 1 + startSize;
    paint.setTextSize(curSize);
    字符串文本= 1 + startSize + - + TEXT_SNIPPET;
    布局=新StaticLayout(文字,
                               涂料,
                               Integer.MAX_VALUE的,
                               Alignment.ALIGN_NORMAL,
                               1.0F,
                               0.0,
                               真正 );

    浮顶= STEP_DISTANCE *我;
    浮动是measuredWidth = layout.getLineMax(0);
    canvas.drawRect(0,顶部,是measuredWidth,顶+ curSize,bgPaint);
    canvas.drawText(文字,0,STEP_DISTANCE * 1 + curSize,油漆);
  }
}
 

解决方案

我也有类似的问题,即测量文本宽度为关闭的一点,一旦你设置字样的油漆,这将消失。 所以,使用油漆对象中的 StaticLayout 刚才设置的字样前:

  textPaint.setTypeface(Typeface.create(无衬线,Typeface.NORMAL))
 

或你想要的任何字体。

I am trying to calculate the width of a multiline text paragraph. To my knowledge, the only class that can do this in Android is the StaticLayout (or DynamicLayout) class. When using this class i do no get the proper length of my text snippet but rather the measured the dimensions are sometimes smaller and sometimes greater depending on the text size.

So i am basically looking for a way to reliably measure the width of a multiline text string.

The following image shows how the measured width diverges from the actual text length in various text sizes.

The screenshot is created running the the following code in a custom View:

@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 );
  }
}

解决方案

I had a similar issue where the measured text width was off by a bit, once you set a Typeface to the paint this will go away. So before you use the paint object in the StaticLayout just set the Typeface:

textPaint.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL))

or whatever typeface you want.

这篇关于如何可靠地确定多行字符串的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆