답변:
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단단히 텍스트를 감싸고있다.
실제로 텍스트를 측정하는 방법에는 세 가지가 있습니다.
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는 동일하며 다른 사용자가 게시 한 측정 값의 고급 너비를 갖습니다. 어떤 사람들은이 공간이 과도하다고 생각합니다. 그러나 이것은 매우 주관적이며 글꼴에 따라 다릅니다.
예를 들어 측정 텍스트 경계의 너비가 실제로 너무 작게 보일 수 있습니다.

그러나 텍스트를 추가 할 때 한 글자의 경계는 정상적으로 보입니다.

글쎄, 나는 다른 방식으로 해왔다.
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 . 거기에 오름차순 등의 다른 텍스트 속성에 대한 간단한 공식도 있습니다.
앱 뿐만 아니라 기능 drawFontTest () 엑셀에서 사용되는 원료 값을 생성하기위한 본 REPO도 가능하다.