描画に使用されたペイントに従って、drawText()メソッドを使用してAndroidキャンバスに描画されるテキストの幅(ピクセル単位)を返すメソッドはありますか?
7 に答える
android.graphics.Paint#measureText(String txt)を見たことがありますか?
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値を含む幅を返します。Rect
によって返される幅にはこのgetTextBounds
パディングがありません。これは、境界がRect
テキストをしっかりと折り返すためです。
テキストを測定する方法は実際には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文字の境界は正常に見えます。
さて、私は別の方法で行いました:
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());
これがお役に立てば幸いです。
メソッドmeasureText()およびgetTextPath()+ computeBounds()を使用して、https://github.com/ArminJo/android-blue-display/blobにある固定サイズフォントのすべてのテキスト属性を使用してExcelを構築しました。 /master/TextWidth.xlsx。そこには、ascendなどの他のテキスト属性の簡単な式もあります。
このリポジトリでは、Excelで使用される生の値を生成するためのアプリと関数drawFontTest()も利用できます。
「textPaint.getTextSize()」を使用してテキスト幅を取得できます