How to set unit for Paint.setTextSize()

I know this topic is old and already answered but I would like to also suggest this piece of code:

int MY_DIP_VALUE = 5; //5dp

int pixel= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                              MY_DIP_VALUE, getResources().getDisplayMetrics());

Convert it like this

// The gesture threshold expressed in dip
private static final float GESTURE_THRESHOLD_DIP = 16.0f;

// Convert the dips to pixels
final float scale = getContext().getResources().getDisplayMetrics().density;
mGestureThreshold = (int) (GESTURE_THRESHOLD_DIP * scale + 0.5f);

// Use mGestureThreshold as a distance in pixels

from here http://developer.android.com/guide/practices/screens_support.html#dips-pels


The accepted answer is for gestures, not setting text size. The highest voted answer (at the time of this writing) is close, but the documentation recommends using sp rather than dp because in addition to being scaled for screen densities (as dp values are), sp is also scaled according to user preferred font sizes.

From an int in code

int spSize = 17;
float scaledSizeInPixels = spSize * getResources().getDisplayMetrics().scaledDensity;
mTextPaint.setTextSize(scaledSizeInPixels);

Or alternatively

int spSize = 17;
float scaledSizeInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
        spSize, getResources().getDisplayMetrics());
mTextPaint.setTextSize(scaledSizeInPixels);

From resources

Or if you have the sp or dp value in resources:

<resources>
    <dimen name="fontSize">17sp</dimen>
</resources>

with

float scaledSizeInPixels = getResources().getDimensionPixelSize(R.dimen.fontSize);
mTextPaint.setTextSize(scaledSizeInPixels);

Other links

  • How to convert DP, PX, SP among each other, especially DP and SP?
  • Android: Canvas.drawText() text size on different screen resolutions
  • Paint.setTextSize
  • getDimensionPixelSize

And here is even shorter method to convert dp-s to px-els taking display metrics into account

https://developer.android.com/reference/android/content/res/Resources.html#getDimensionPixelSize(int)


If your Paint object is being used to draw text on a Canvas, you can let the Canvas handle scaling for you.

When calling Canvas.drawText() the text size is first determined by the passed in Paint object, which can be set via Paint.setTextSize(). The text size is automatically scaled by Canvas based on the canvas density, which can be found using Canvas.getDensity().

When setting the text size on a paint object that will be drawn on Canvas, work with a unit value of dp or sp and let Canvas handle the scaling for you.