Is it possible to change the unit for
Paint.setTextSize()? As far as I know, it’s pixel but I like to set the text size in DIP for multiple screen support.
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
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());
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.
int in code
int spSize = 17; float scaledSizeInPixels = spSize * getResources().getDisplayMetrics().scaledDensity; mTextPaint.setTextSize(scaledSizeInPixels);
int spSize = 17; float scaledSizeInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spSize, getResources().getDisplayMetrics()); mTextPaint.setTextSize(scaledSizeInPixels);
Or if you have the
dp value in resources:
<resources> <dimen name="fontSize">17sp</dimen> </resources>
float scaledSizeInPixels = getResources().getDimensionPixelSize(R.dimen.fontSize); mTextPaint.setTextSize(scaledSizeInPixels);
And here is even shorter method to convert dp-s to px-els taking display metrics into account
If your Paint object is being used to draw text on a Canvas, you can let the Canvas handle scaling for you.
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
When setting the text size on a paint object that will be drawn on Canvas, work with a unit value of
sp and let Canvas handle the scaling for you.