Android: Canvas.drawText() is inconsistent across multiple screen resolutions and densities

2 comments

I'm not sure why this was done this way, but the default font size in the Paint object does not scale automatically when you run your app on different resolutions and screen densities.

A thing to keep in mind is that if a Paint object is to be used for Canvas.drawText() then it has to be initialised for the right screen density.

If you want to keep the current default size but scale it according to the screen density, simply add this line of code.

paint.setTextSize(paint.getTextSize() * yourActivity.getApplicationContext().getResources().getDisplayMetrics().density);

This will slightly scale it up or down, depending on whether the device is running at low or high density.

If you want to have more control over the size of the text, then use a dimension resource. In your "res/values" folder, either add to or create an XML file.

Using the editor, create a new "Dimension" value in that XML file with whatever name you want. For this example, I'm going to give it a value of "16sp". This means that it will be "16 scaled pixels" big, scaled to the device density AND the user's font size settings.

To apply that dimension:

paint.setTextSize(yourActivity.getApplicationContext().getResources().getDimensionPixelSize(R.dimen.float_text_size));

Kudos to Marcin Gil and Joseph Earl for the help, but it ended up being my own noobish mistake for not applying it to the right Paint instance.

92419_1

Sources

2 comments:

  1. Thanks mate! This saved my day.

    ReplyDelete
  2. Hey man I'm a traiee. My boss might have killed me.
    Thank you!!

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog