如何为Paint.setTextSize()设置单位

Yve*_*man 55 java android view

是否可以更改单位Paint.setTextSize()?据我所知,它是像素,但我喜欢在DIP中设置文本大小以支持多屏幕.

Fel*_*das 89

我知道这个主题很老,已经回答了,但我还想建议这段代码:

int MY_DIP_VALUE = 5; //5dp

int pixel= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                              MY_DIP_VALUE, getResources().getDisplayMetrics());
Run Code Online (Sandbox Code Playgroud)


Ale*_*voy 45

像这样转换它

// 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
Run Code Online (Sandbox Code Playgroud)

从这里http://developer.android.com/guide/practices/screens_support.html#dips-pels


Sur*_*gch 23

接受的答案是手势,而不是设置文字大小.最高投票答案(在撰写本文时)很接近,但文档建议使用sp而不是dp因为除了按屏幕密度(如dp值)进行缩放之外,sp还根据用户首选字体大小进行缩放.

int代码中

int spSize = 17;
float scaledSizeInPixels = spSize * getResources().getDisplayMetrics().scaledDensity;
mTextPaint.setTextSize(scaledSizeInPixels);
Run Code Online (Sandbox Code Playgroud)

或者

int spSize = 17;
float scaledSizeInPixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
        spSize, getResources().getDisplayMetrics());
mTextPaint.setTextSize(scaledSizeInPixels);
Run Code Online (Sandbox Code Playgroud)

来自资源

或者,如果您拥有资源中的值spdp值:

<resources>
    <dimen name="fontSize">17sp</dimen>
</resources>
Run Code Online (Sandbox Code Playgroud)

float scaledSizeInPixels = getResources().getDimensionPixelSize(R.dimen.fontSize);
mTextPaint.setTextSize(scaledSizeInPixels);
Run Code Online (Sandbox Code Playgroud)

其他链接