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

Nio*_*199 125 android text draw android-canvas

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

Mar*_*ein 215

你看过android.graphics.Paint.measureText(String txt)吗?

  • 谢谢就是这样!我不知道为什么我会跳过它.目的是简单地在屏幕中央绘制文本.无论如何,我刚刚意识到我也可以在用于绘制文本的Paint上使用setTextAlign(Align.CENTER),它将指定的原点移动到绘制文本的中心.谢谢. (18认同)
  • 太棒了,谢谢,在油漆上设置对齐!谁会想到这个......? (2认同)

小智 31

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();
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 11

补充答案

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

资源


Jim*_*aca 5

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

获取文本边界:

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()
Run Code Online (Sandbox Code Playgroud)

测量文本宽度:

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)
Run Code Online (Sandbox Code Playgroud)

和 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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

测量文本边界看起来很小

但是,当添加附加文本时,一个字母的边界看起来很正常: 测量字符串的文本边界看起来很正常

图片取自Android Developers Guide to Custom Canvas Drawing