11

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?

Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
lorraine batol
  • 6,001
  • 16
  • 55
  • 114

3 Answers3

21

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

float twelveDp = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 12, 
                mContext.getResources().getDisplayMetrics() );
Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
SleepyTonic
  • 506
  • 5
  • 11
  • applyDimension (int unit, FLOAT value...) not DP. This solution convert float to float, not DP to float. – Cipo Apr 08 '22 at 08:38
9

Try this:

public static float dipToPixels(Context context, float dipValue){
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  dipValue, metrics);
}
Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
Sachin Suthar
  • 692
  • 10
  • 28
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>
grigorz
  • 31
  • 4