Android: Canvas.drawText() text size on different screen resolutions

twig picture twig · Mar 20, 2011 · Viewed 30.9k times · Source

For my Android game I have some calls to Canvas.drawText().

For testing, I use the standard font size which seems to be working fine.

However, when I bump up the resolution to a higher density, the larger images are automatically loaded but the text is now incredibly small.

Is there an easy way to calculate what size the text should be drawn at or am I bound to do this manually?

edit: What was the point of editing my post @Suragch ?

Answer

Joseph Earl picture Joseph Earl · Mar 20, 2011

The easiest way is to define your font sizes in your resources with the units of scale-independent pixels (sp) -- this unit is like density independent pixels (dp or dip) in that it takes into account the screen density but it also takes into account the font-size setting of the user.

To add a new dimension create a dimens.xml file in your res/values folder and enter the following code to add a new dimension with the name myFontSize:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="myFontSize">20sp</dimen>
</resources>

You can then get the text size in your application using

int scaledSize = getResources().getDimensionPixelSize(R.dimen.myFontSize);

The resulting size will be correctly scaled to take into account the current screen density and font-size setting.

For more information see the Android Developers page on More Resources.