如何根据设备宽度和字体大小测量TextView高度?

时间:2013-01-11 11:07:19

标签: android android-layout android-canvas android-view textview

我正在Android中寻找输入(text,text_font_size,device_width)的方法,根据这些计算,它将返回显示特定文本所需的高度?

我正在根据他的内容设置文本视图/ webview高度运行时,我知道warp内容,但由于某些Web视图最小高度问题,我无法使用。

所以我试图计算高度,并根据我设置视图高度。

我尝试过以下方式

Paint paint = new Paint();
paint.setTextSize(text.length()); 
Rect bounds = new Rect();
paint.getTextBounds(text, 0, 1, bounds);
mTextViewHeight= bounds.height();

所以输出是

1)“Hello World”返回字体15的高度13

2)“Jelly Bean的最新版本在这里,性能优化”返回字体15的高度16

然后我尝试了

Paint paint = new Paint();
paint.setTextSize(15);
paint.setTypeface(Typeface.SANS_SERIF);
paint.setColor(Color.BLACK);

Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), result);

Paint.FontMetrics metrics = brush.getFontMetrics();
int totalHeight = (int) (metrics.descent - metrics.ascent + metrics.leading);

所以输出是

1)“Hello World”返回字体15的高度17

2)“Jelly Bean的最新版本在这里,性能优化”为字体15返回高度17

如果我将这些值设置为我的视图,那么它会剪切一些文本,而不显示所有内容。

在某些桌子上它看起来还不错,因为它的宽度很大,但手机上没有。

有没有办法根据内容计算身高?

3 个答案:

答案 0 :(得分:47)

public static int getHeight(Context context, String text, int textSize, int deviceWidth) {
    TextView textView = new TextView(context);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.AT_MOST);
    int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    textView.measure(widthMeasureSpec, heightMeasureSpec);
    return textView.getMeasuredHeight();
}

如果未以像素为单位给出textSize,请更改setTextSize()的第一个参数。

答案 1 :(得分:8)

我有一种更简单的方法可以在绘画之前知道线条的真实高度,我不知道这对你们有什么帮助,但是我的解决方案可以获得线条的高度#39 ; s独立于布局的高度,只需采用如下字体指标:

myTextView.getPaint().getFontMetrics().bottom - myTextView.getPaint().getFontMetrics().top)

我们得到字体从要绘制的textview中获取的真实高度。这不会给你一个int,但是你可以让Math.round得到一个接近的值。

答案 2 :(得分:7)

Paint.getTextBounds()不会让您失望。详细信息为here

相反,您可以尝试这种方式:

int mMeasuredHeight = (new StaticLayout(mMeasuredText, mPaint, targetWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true)).getHeight();
相关问题