ChatGPT解决这个技术问题 Extra ChatGPT

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

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


M
Mahozad

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


谢谢就是这个!我不知道我为什么跳过它。目的是简单地在屏幕中央绘制文本。无论如何,我刚刚意识到我也可以在用于绘制文本的 Paint 上使用 setTextAlign(Align.CENTER),它将指定的原点移动到绘制文本的中心。谢谢。
太好了,谢谢,在油漆上设置对齐!谁会想到……?
或者您可以将 textview 的 Gravity 设置为 Center
P
Paresh J
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();

C
Community

补充答案

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

source


J
Jim Baca

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

获取文本边界:

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

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

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

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

https://i.stack.imgur.com/HsJ9Z.png

https://i.stack.imgur.com/aKM8k.png

图片取自 Android Developers Guide to Custom Canvas Drawing


H
Hiren Patel

好吧,我以不同的方式完成了:

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

希望这会帮助你。


A
Armin J.

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

app 以及用于生成 excel 中使用的原始值的函数 drawFontTest() 也可在此 repo 中使用。


因为字距调整(字母之间的间距)取决于单个字母序列,所以这可能仅适用于像 Courier 这样的固定字体。
A
Ashish John

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