2010-07-15 84 views

回答

183
+18

感谢这是它!我不知道为什么我跳过它。 目的是简单地在屏幕中心画一个文本。 无论如何,我只是意识到我也可以在用于绘制文本的Paint上使用setTextAlign(Align.CENTER),它将指定的原点移动到绘制文本的中心。 谢谢。 – NioX5199 2010-07-15 16:17:44

+2

非常好,谢谢,设置对齐油漆!谁会想到...? – 2011-08-05 02:22:58

+0

或者您可以将文本视图的重力设置为中心 – yeradis 2011-10-21 14:38:14

22
Paint paint = new Paint(); 
Rect bounds = new Rect(); 

int text_height = 0; 
int text_width = 0; 

paint.setTypeface(Typeface.DEFAULT);// your preference here 
paint.setTextSize(25);// have this the same as your text size 

String text = "Some random text"; 

paint.getTextBounds(text, 0, text.length(), bounds); 

text_height = bounds.height(); 
text_width = bounds.width(); 
-1

你可以使用 “textPaint.getTextSize()” 获得文字宽度

1

嗯,我在不同的方式这样做:

String finalVal ="Hiren Patel"; 

Paint paint = new Paint(); 
paint.setTextSize(40); 
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(finalVal, 0, finalVal.length(), result); 

Log.i("Text dimensions", "Width: "+result.width()+"-Height: "+result.height()); 

希望这会帮助你。

4

补充答案

有由Paint.measureTextPaint.getTextBounds返回的宽度之间的微小差异。 measureText返回一个宽度,其中包括填充字符串开头和结尾的字形的advanceX值。 getTextBounds返回的Rect宽度没有此填充,因为边界是Rect,它严格包装文本。

source

+0

是的,这是更确切的。谢谢。 – chksr 2017-10-17 13:50:01