android - convert dp to float

2019-05-13 06:13发布

My font size is 12dp.

I'm setting the font using TextPaint, since I'm using a span. The problem is the parameter that TextPaint accepts is in float. I'm wondering how can I convert 12 dp to float?

3条回答
叼着烟拽天下
2楼-- · 2019-05-13 06:52

From android.content.res.Resources.getDimension(int id):

float twelveDp = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 12, 
                mContext.getResources().getDisplayMetrics() );
查看更多
乱世女痞
3楼-- · 2019-05-13 07:06

You can try following:

// Convert the sp to pixels

final float scale = getResources().getDisplayMetrics().scaledDensity;
int mTextSizeP = (int)  getResources().getDimensionPixelSize(R.dimen.text_size) / scale );

I have already have text_size defined in res/values/dimens.xml :

<resources>
    <dimen name="text_size">12sp</dimen>
</resources>
查看更多
贼婆χ
4楼-- · 2019-05-13 07:11

Try this:

public static float dipToPixels(Context context, float dipValue){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  dipValue, metrics);
}
查看更多
登录 后发表回答