Android: How to use scaled pixel or font point sizes as pixel dimensions for Paint.setTextSize() and Canvas.drawText()

Android supports a whole heap of dimensions such as density independent pixels (dp), scaled independent pixels (sp), font points (pt), raw pixels (px), millimetres (mm) or inches (in). See more information about them in the documentation.

However, rather than having to calculate all of those manually and causing a whole lot of mindfuck to the dev community, they've provided some rather simple methods of working out these values.

Google have prevented this backlash from developers.

Using Resources.getDimensionPixelSize(), we can convert any dimension into a raw pixel value. This ensures that Paint.setTextSize() will display the same across all devices.

Creating the resource

First, create an Android XML file resource under  "res/values" called "dimensions.xml" of resource type "value".

Using the editor, add a new Dimension of any name and the value of your choice (ie. 20pt).

<?xml version="1.0" encoding="utf-8"?>
<dimen name="custom_text_size">16sp</dimen>

Using the dimension

Now to use this value in your code.

m_paint = new Paint();

Then just use that Paint object in the Canvas.drawText() call.

Remember to use Paint.ANTI_ALIAS_FLAG to ensure that the text looks good!

[ Android dimensions docs, StackOverflow ]

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