有没有一种方法可以根据绘制文本时使用的drawText()方法返回要在Android canvas上绘制的文本的宽度(以像素为单位)?
发布于 2010-07-16 00:02:40
您看过android.graphics.Paint#measureText(String txt)(http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String%29)?
发布于 2014-11-17 22:54:10
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();
发布于 2019-08-20 10:43:11
实际上,有三种不同的方法来测量文本。
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是相等的,并且具有其他人发布的测量的高级宽度。有些人认为这个空间太大了。然而,这是非常主观的,并且依赖于字体。
例如,测量文本边界的宽度实际上可能看起来太小:
但是,当添加额外的文本时,一个字母的边界看起来很正常:
https://stackoverflow.com/questions/3257293
复制相似问题