0

i have tried below cosde is working 4.0 but not working in 4.0 above , how to convert pt to sp for setting textview font size.

public static int pixelsToSp(int pt) {

        DisplayMetrics metrics = new DisplayMetrics();

        return (int) (pt * metrics.densityDpi / metrics.scaledDensity);
    }
venu
  • 2,971
  • 6
  • 40
  • 59

2 Answers2

1
// We need to get some Android resources from conext in order to calculate proper pixel dimensions from sp
Resources resources = getResources();
// Calculate pixel dimension
int pixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, your_sp_value, resources.getDisplayMetrics());

I've used this to calculate pixels from dip and it has worked like a charm, but you must have access to context in order to get resources needed.

Robert
  • 4,602
  • 4
  • 22
  • 33
0

You'll need access to a context.

float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return pt/scaledDensity;
James McCracken
  • 15,488
  • 5
  • 54
  • 62