android - convert dp to float

和自甴很熟 提交于 2020-01-02 05:59:47

问题


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?


回答1:


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

float twelveDp = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 12, 
                mContext.getResources().getDisplayMetrics() );



回答2:


Try this:

public static float dipToPixels(Context context, float dipValue){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  dipValue, metrics);
}



回答3:


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>


来源:https://stackoverflow.com/questions/13600802/android-convert-dp-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!