开发者

How to set unit for Paint.setTextSize()

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 si开发者_如何学运维ze in DIP for multiple screen support.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜