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

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


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.


You can do it yourself using a simple math operation:

You need to calculate a relation that draws your text just the same size for any canvas size, so use the actual canvas size, like this:

double relation = Math.sqrt(canvas.getWidth() * canvas.getHeight());

But that number is just too big, so divide it by one that suits your needs, lets say 250:

relation = relation / 250;

Now you can set your text size like this:

paint.setTextSize((float) (myFontSize * relation));

You don't have to necessary divide relation by any number but in that case you will have to use very small font sizes for the variable myFontSize. For me 250 works just fine to use regular font sizes that will adjust to any screen size, since you are already taking in count the pixels dimension from your canvas.


The easiest way is to define your font size in your resources directory with the units of scale-independent pixel (sp) or the density-independent pixel (dp). Then get the text size using

int scaledSize = getResources().getDimensionPixelSize(R.dimen.font_size);mTextView.setTextSize(scaledSize);

This will scale the text-size appropriately according to the current screen density/resolution and the user's font-size setting.

How to define font size in resource directory?

Create a file named dimens.xml in the folder res->values. Then copy the following code.

<resources>    <dimen name="font_size">25sp</dimen>   // sp or dp accordingly</resources>

The name attribute of the tag <dimen> will be used as resource ID.