测量Canvas(Android)上绘制的文本宽度

时间:2010-07-15 15:45:53

标签: android text android-canvas draw

是否有一种方法可以根据用于绘制它的Paint使用drawText()方法返回要在Android画布上绘制的文本的宽度(以像素为单位)?

7 个答案:

答案 0 :(得分:206)

答案 1 :(得分:28)

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();

答案 2 :(得分:8)

补充答案

Paint.measureTextPaint.getTextBounds返回的宽度略有不同。 measureText返回一个宽度,其中包含填充字符串开头和结尾的字形的advanceX值。 Rect返回的getTextBounds宽度没有此填充,因为边界是紧密包装文本的Rect

source

答案 3 :(得分: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 :(得分:1)

实际上有三种测量文本的方法。

GetTextBounds:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
paint.getTextBounds(contents, 0, 1, rect)
val width = rect.width()

MeasureTextWidth:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val width = paint.measureText(contents, 0, 1)

和getTextWidths:

val paint = Paint()
paint.typeface = ResourcesCompat.getFont(context, R.font.kaushanscript)
paint.textSize = 500f
paint.color = Color.argb(255, 3, 221, 252)
val contents = "g"
val rect = Rect()
val arry = FloatArray(contents.length)
paint.getTextBounds(contents, 0, contents.length, rect)
paint.getTextWidths(contents, 0, contents.length, arry)
val width = ary.sum()

请注意,如果您尝试确定何时将文本换行到下一行,则getTextWidths可能会有用。

measureTextWidth和getTextWidth相等,并且具有其他人发布的度量的高级宽度。有些人认为此空间过大。但是,这是非常主观的,并且取决于字体。

例如,小节文本边界的宽度实际上看起来太小:

measure text bounds looks small

但是,当添加其他文本时,一个字母的边界看起来很正常: measure text bounds looks normal for strings

Android Developers Guide to Custom Canvas Drawing拍摄的图像

答案 5 :(得分:0)

我使用了方法measureText()和getTextPath()+ computeBounds(),并构建了一个Excel,其中包含可在https://github.com/ArminJo/android-blue-display/blob/master/TextWidth.xlsx下找到的固定大小字体的所有文本属性。 在那里你会发现其他文本属性的简单公式,如提升等。

此repo中还提供了app以及用于生成excel中使用的原始值的函数drawFontTest()

答案 6 :(得分:-1)

您可以使用“textPaint.getTextSize()”来获取文字宽度