135

描画に使用されたペイントに従って、drawText()メソッドを使用してAndroidキャンバスに描画されるテキストの幅(ピクセル単位)を返すメソッドはありますか?

4

7 に答える 7

246

android.graphics.Paint#measureText(String txt)を見たことがありますか?

于 2010-07-15T16:02:40.473 に答える
35
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();
于 2014-11-17T14:54:10.293 に答える
16

補足回答

とによって返される幅にはわずかな違いが Paint.measureTextありPaint.getTextBoundsます。measureText文字列の最初と最後を埋めるグリフのadvanceX値を含む幅を返します。Rectによって返される幅にはこのgetTextBoundsパディングがありません。これは、境界がRectテキストをしっかりと折り返すためです。

ソース

于 2017-02-02T07:05:26.360 に答える
5

テキストを測定する方法は実際には3つあります。

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は等しく、他の人が投稿したメジャーの高度な幅を持っています。このスペースは過剰だと考える人もいます。ただし、これは非常に主観的であり、フォントによって異なります。

たとえば、メジャーテキストの境界からの幅は実際には小さすぎるように見える場合があります。

テキストの境界を測定すると小さく見えます

ただし、テキストを追加すると、1文字の境界は正常に見えます。 文字列のテキスト境界の測定は正常に見えます

Android開発者ガイドからカスタムキャンバス描画に取得した画像

于 2019-08-20T02:43:11.403 に答える
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());

これがお役に立てば幸いです。

于 2016-12-09T11:03:30.147 に答える
0

メソッドmeasureText()およびgetTextPath()+ computeBounds()を使用して、https://github.com/ArminJo/android-blue-display/blobにある固定サイズフォントのすべてのテキスト属性を使用してExcelを構築しました。 /master/TextWidth.xlsx。そこには、ascendなどの他のテキスト属性の簡単な式もあります。

このリポジトリでは、Excelで使用される生の値を生成するためのアプリと関数drawFontTest()も利用できます。

于 2015-09-20T09:23:56.163 に答える
0

「textPaint.getTextSize()」を使用してテキスト幅を取得できます

于 2016-03-16T14:35:41.613 に答える