Browse Source

Fix dp to pixel conversion

Copied a bad answer from stack overflow 🤦‍♂️
Guy Carmeli 6 years ago
parent
commit
8a60399a44

+ 7
- 7
lib/android/app/src/main/java/com/reactnativenavigation/utils/UiUtils.java View File

7
 import android.os.Looper;
7
 import android.os.Looper;
8
 import android.support.annotation.NonNull;
8
 import android.support.annotation.NonNull;
9
 import android.util.DisplayMetrics;
9
 import android.util.DisplayMetrics;
10
-import android.util.TypedValue;
11
 import android.view.View;
10
 import android.view.View;
12
 import android.view.ViewTreeObserver;
11
 import android.view.ViewTreeObserver;
13
 import android.view.WindowManager;
12
 import android.view.WindowManager;
98
     }
97
     }
99
 
98
 
100
     public static float dpToPx(Context context, float dp) {
99
     public static float dpToPx(Context context, float dp) {
101
-        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, dp,
102
-                context.getResources().getDisplayMetrics());
100
+        Resources resources = context.getResources();
101
+        DisplayMetrics metrics = resources.getDisplayMetrics();
102
+        return dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
103
     }
103
     }
104
 
104
 
105
     public static int dpToPx(Context context, int dp) {
105
     public static int dpToPx(Context context, int dp) {
106
-        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, dp,
107
-                context.getResources().getDisplayMetrics());
106
+        Resources resources = context.getResources();
107
+        DisplayMetrics metrics = resources.getDisplayMetrics();
108
+        return (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
108
     }
109
     }
109
 
110
 
110
     public static float pxToDp(Context context, float px) {
111
     public static float pxToDp(Context context, float px) {
111
-        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px,
112
-                context.getResources().getDisplayMetrics());
112
+        return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
113
     }
113
     }
114
 
114
 
115
     public static float dpToSp(Context context, float dp) {
115
     public static float dpToSp(Context context, float dp) {