如何在Android上获取字符串宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3630086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get string width on Android?
提问by Mikael Lindl?f
I would like to get height too if possible.
如果可能的话,我也想获得高度。
回答by Frank
You can use the getTextBounds(String text, int start, int end, Rect bounds)
method of a Paint object. You can either use the paint object supplied by a TextView
or build one yourself with your desired text appearance.
您可以使用getTextBounds(String text, int start, int end, Rect bounds)
Paint 对象的方法。您可以使用 a 提供的绘制对象,也可以TextView
自己构建具有所需文本外观的绘制对象。
Using a Textview you Can do the following:
使用 Textview 您可以执行以下操作:
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();
回答by SharkAlley
If you just need the width you can use:
如果您只需要宽度,您可以使用:
float width = paint.measureText(string);
http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)
http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String)
回答by arberg
There are two different width measures for a text. One is the number of pixels which has been drawn in the width, the other is the number of 'pixels' the cursor should be advanced after drawing the text.
文本有两种不同的宽度度量。一个是宽度中已绘制的像素数,另一个是绘制文本后光标应前进的“像素”数。
paint.measureTextand paint.getTextWidthsreturns the number of pixels (in float) which the cursor should be advanced after drawing the given string. For the number of pixels painted use paint.getTextBounds as mentioned in other answer. I believe this is called the 'Advance' of the font.
Paint.measureText和paint.getTextWidths返回在绘制给定字符串后光标应前进的像素数(浮点数)。对于绘制的像素数,请使用其他答案中提到的paint.getTextBounds。我相信这被称为字体的“高级”。
For some fonts these two measurements differ (alot), for instance the font Black Chanceryhave letters which extend past the other letters (overlapping) - see the capital 'L'. Use paint.getTextBoundsas mentioned in other answer to get pixels painted.
对于某些字体,这两种度量不同(很多),例如字体Black Chancery 的字母延伸到其他字母之外(重叠) - 参见大写的“L”。使用其他答案中提到的paint.getTextBounds来绘制像素。
回答by Hiren Patel
I have measured width in this way:
我以这种方式测量了宽度:
String str ="Hiren Patel";
Paint paint = new Paint();
paint.setTextSize(20);
Typeface typeface = Typeface.createFromAsset(getAssets(), "Helvetica.ttf");
paint.setTypeface(typeface);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
Rect result = new Rect();
paint.getTextBounds(str, 0, str.length(), result);
Log.i("Text dimensions", "Width: "+result.width());
This would help you.
这会帮助你。
回答by qix
Most likely you want to know the painted dimensions for a given string of text with a given font (i.e. a particular Typeface
such as the “sans-serif” font family with a BOLD_ITALIC style, and particular size in sp or px).
很可能您想知道给定字体的给定文本字符串的绘制尺寸(即特定Typeface
字体,例如具有 BOLD_ITALIC 样式的“sans-serif”字体系列,以及以 sp 或 px 为单位的特定大小)。
Rather than inflating a full-blown TextView
, you can go lower level and work with a Paint
object directly for single-linetext, for example:
与其夸大一个完整的TextView
,您可以降低级别并Paint
直接使用对象来处理单行文本,例如:
// Maybe you want to construct a (possibly static) member for repeated computations
Paint paint = new Paint();
// You can load a font family from an asset, and then pick a specific style:
//Typeface plain = Typeface.createFromAsset(assetManager, pathToFont);
//Typeface bold = Typeface.create(plain, Typeface.DEFAULT_BOLD);
// Or just reference a system font:
paint.setTypeface(Typeface.create("sans-serif",Typeface.BOLD));
// Don't forget to specify your target font size. You can load from a resource:
//float scaledSizeInPixels = context.getResources().getDimensionPixelSize(R.dimen.mediumFontSize);
// Or just compute it fully in code:
int spSize = 18;
float scaledSizeInPixels = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP,
spSize,
context.getResources().getDisplayMetrics());
paint.setTextSize(scaledSizeInPixels);
// Now compute!
Rect bounds = new Rect();
String myString = "Some string to measure";
paint.getTextBounds(myString, 0, myString.length(), bounds);
Log.d(TAG, "width: " + bounds.width() + " height: " + bounds.height());
??For multi-line or spanned text(SpannedString
), consider using a StaticLayout
, in which you provide the width and derive the height. For ?a very elaborate answer on measuring and drawing text to a canvas in a custom view doing that, see: https://stackoverflow.com/a/41779935/954643
??对于多行或跨行文本( SpannedString
),请考虑使用 a StaticLayout
,在其中提供宽度并导出高度。有关在自定义视图中测量和绘制文本到画布的非常详细的答案,请参阅:https: //stackoverflow.com/a/41779935/954643
Also worth noting @arberg's reply below about the pixels painted vs the advance width ("number of pixels (in float) which the cursor should be advanced after drawing the given string"), in case you need to deal with that.
还值得注意的是@arberg 在下面关于绘制的像素与前进宽度的回复(“绘制给定字符串后光标应前进的像素数(浮点数)”),以防您需要处理该问题。
回答by Serj Ardovic
I'd like to share a better way (more versatile then the current accepted answer)of getting the exact width of a drawn text (String
) with the use of static class StaticLayout
:
我想分享一种更好的方法(比当前接受的答案更通用String
)使用静态类获取绘制文本 ( )的确切宽度StaticLayout
:
StaticLayout.getDesiredWidth(text, textPaint))
this method is more accurate than textView.getTextBounds()
, since you can calculate width of a single line in a multiline TextView
, or you might not use TextView
to begin with (for example in a custom View
implementation).
此方法比 更准确textView.getTextBounds()
,因为您可以计算多行中单行的宽度TextView
,或者您可能不使用TextView
开始(例如在自定义View
实现中)。
This way is similar to textPaint.measureText(text)
, however it seems to be more accurate in rare cases.
这种方式类似于textPaint.measureText(text)
,但在极少数情况下似乎更准确。