Friday, March 22, 2013

Scale text in code, regardless of screen size/density


While tinkering with TextViews, sometimes I just needed scale-able text for every device, every density.  I scoured Stack Overflow and various places, but couldn't seem to land in the right spot.  It would really show when running on a Kindle Fire and seemed like there should be a simple solution, and in some ways it is.  You can set text sizes in XML files which isn't bad, but I wanted to control it by percentage in code and basically on the fly.  Hiding in the shadows of a question, I found this lonely unchecked answer by Mark-1688382n



"I have played with this for quite some time, trying to get my font sizes correct on a wide variety of 7" tablets (kindle fire, Nexus7, and some inexpensive ones in China with low-res screens) and devices.
The approach that finally worked for me is as follows. The "32" is an arbitrary factor that basically gives about 70+ characters across a 7" tablet horizontal line, which is a font size I was looking for. Adjust accordingly."

Mark-1688382
http://stackoverflow.com/questions/2596452/how-to-scale-resize-text-to-fit-a-textview/14242816#14242816

I didn't really want to modify it much because it worked fantastically, so I just added a few tweaks.  I could have swapped my incoming var with the 32.f, but got used to the way I changed it for all intents and purposes.  Here is the way I call it.

    smallT=getFontSize (this,1.2f);
    medT=getFontSize (this,1.80f);

and here is the code to let her rip.  You could really modify this any way you wish if you wish to scale your text to an exact percentage of the screen.




Hopefully this can help someone if they need scale-able text.  As usual, feel free to show your support by downloading my apps from the android,blackberry, or amazon market under A54studio.

A54studio on Amazon

A54studio on Play

A54studio on Blackberry



No comments:

Post a Comment