是否有一种方法可以返回使用drawText()方法在Android画布上绘制文本时,根据用于绘制的Paint,文本的宽度(以像素为单位)?
是否有一种方法可以返回使用drawText()方法在Android画布上绘制文本时,根据用于绘制的Paint,文本的宽度(以像素为单位)?
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();
补充回答
Paint.measureText
和Paint.getTextBounds
返回的宽度略有不同。 measureText
返回的宽度包括字形的advanceX值填充字符串的开头和结尾。由getTextBounds
返回的Rect
宽度没有这种填充,因为边界是紧密包裹文本的Rect
。
实际上,有三种不同的方法来测量文本。
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()
测量文本宽度:
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()
我使用了measureText()和getTextPath()+computeBounds()方法,并创建了一个Excel表格,其中包含所有固定大小字体的文本属性,可以在https://github.com/ArminJo/android-blue-display/blob/master/TextWidth.xlsx中找到。 在那里,您还会发现其他文本属性(如上升等)的简单公式。
应用程序以及用于生成Excel中使用的原始值的drawFontTest()函数也可在此存储库中找到。
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());
这应该可以工作。
fun String.getWidth(fontSize: Float): Float {
val textPaint = TextPaint()
textPaint.textSize = fontSize
textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
return textPaint.measureText(this)
}
fun String.getWidth(fontSize: Float): Float {
val textPaint = TextPaint()
textPaint.textSize = fontSize
textPaint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
val texts = this.split("\n")
if (texts.size == 1) {
return textPaint.measureText(this)
}
var finalWidth = 0f
for (text in texts) {
val thisLineWidth = text.getWidth(fontSize)
if (thisLineWidth > finalWidth) {
finalWidth = thisLineWidth
}
}
return finalWidth
}