Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
code sample
* Sets the text size for a Paint object so a given string of text will be a
* given width.
* @param paint the Paint to set the text size for
* @param desiredView the desired view
* @param text the text that should be that width
private static float setTextSizeByWidth(Paint paint, View desiredView,
String text) {
// Pick a reasonably large value for the test. Larger values produce
// more accurate results, but may cause problems with hardware
// acceleration. But there are workarounds for that, too; refer to
final float testTextSize = 90f;
// Get the bounds of the text, using our testTextSize.
Rect bounds = new Rect();
String tmpText = " " + text + " ";
paint.getTextBounds(tmpText, 0, tmpText.length(), bounds);
// Calculate the desired size as a proportion of our testTextSize.
float desiredTextSizeX = testTextSize * desiredView.getWidth() / bounds.width();
float desiredTextSizeY = testTextSize * desiredView.getHeight() / bounds.height() * 1000;
// desiredTextSizeX = desiredTextSizeX ;
float desiredTextSize = Math.min(desiredTextSizeX, desiredTextSizeY);
// Set the paint for that size.
return desiredTextSize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.