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

Mac*_*Mac 21 android textview android-layout android-canvas android-view

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

所以输出是

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

所以输出是

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

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

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

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

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

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

如果textSize未以像素给出,请更改第一个参数setTextSize().


jfc*_*ato 8

我有一个更简单的方法来了解画线前的真实高度,我不知道这对你们有什么帮助,但我的解决方案是获得一条线的高度它与布局的高度无关,只是采取像这样的字体指标:

myTextView.getPaint().getFontMetrics().bottom - myTextView.getPaint().getFontMetrics().top)
Run Code Online (Sandbox Code Playgroud)

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


Pri*_*off 7

Paint.getTextBounds()回报不是你所期望的.细节在这里.

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

int mMeasuredHeight = (new StaticLayout(mMeasuredText, mPaint, targetWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true)).getHeight();
Run Code Online (Sandbox Code Playgroud)