Skip to content

Instantly share code, notes, and snippets.

@CrandellWS
Created March 13, 2017 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrandellWS/651b826e0d333ec134a686fd0b1ffdab to your computer and use it in GitHub Desktop.
Save CrandellWS/651b826e0d333ec134a686fd0b1ffdab to your computer and use it in GitHub Desktop.
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
// http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
final float testTextSize = 90f;
// Get the bounds of the text, using our testTextSize.
paint.setTextSize(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.
paint.setTextSize(desiredTextSize);
return desiredTextSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment