How to Get String Width on Android

How to get string width on Android?

You can use the getTextBounds(String text, int start, int end, Rect bounds) method of a Paint object. You can either use the paint object supplied by a TextView or build one yourself with your desired text appearance.

Using a Textview you Can do the following:

Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();

Calculating width of a string on Android

use this code

 Rect bounds = new Rect(); 
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text, 0, text.length(), bounds);
int height = bounds.height();
int width = bounds.width();

How to calculate string font width in pixels?

Looks like there is a measureText method available on Paint. I also found an example:

mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(5);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setTextSize(64);
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.ITALIC));
// ...
float w = mPaint.measureText(text, 0, text.length());

How to get a pixel width of a string in android?

I dont tried, but maybe something like that:

mPaint = new Paint();
mPaint.setTextSize(64);
//...
float width = mPaint.measureText(text, 0, text.length());

Measuring string width to properly size Text() composable

You can use SubcomposeLayout like this:

@Composable
fun MeasureUnconstrainedViewWidth(
viewToMeasure: @Composable () -> Unit,
content: @Composable (measuredWidth: Dp) -> Unit,
) {
SubcomposeLayout { constraints ->
val measuredWidth = subcompose("viewToMeasure", viewToMeasure)[0]
.measure(Constraints()).width.toDp()

val contentPlaceable = subcompose("content") {
content(measuredWidth)
}[0].measure(constraints)
layout(contentPlaceable.width, contentPlaceable.height) {
contentPlaceable.place(0, 0)
}
}
}

Then use it in your view:

MeasureUnconstrainedViewWidth(
viewToMeasure = {
Text("your sample text")
}
) { measuredWidth ->
// use measuredWidth to create your view
}

How to calculate the width of the string

Try this code, I hope it will help you..

Paint paint= new Paint(); 
paint.setTextSize(size);
int txtWidth = (int)(paint.measureText("Hello how are you?"));


Related Topics



Leave a reply



Submit