Files
react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/PixelUtil.java
T
David Vacca 6d4fff2e5c Fix android view dimensions
Summary:
This diff fixes the Android View dimensions in VR

PixelUtil.toSPFromPixel and PixelUtil.getDisplayMetricDensity() are both using getScreenDisplayMetrics() to perform conversion of dimensions. This is not correct because we should take into consideration the density of the Context / Activity instead of the Screen. This problem didn't raise before in Fabric Android because it seems that android OS on phones usually share the scale between the screen and the Activity?

These two methods are only used in Fabric and they were introduced by D9583972 (https://github.com/facebook/react-native/commit/5c0da011cbaa788c52519f8091157ca6d87d8abb) and D9173758 (https://github.com/facebook/react-native/commit/8b5e3fc16b1e58441318b6ada629dcff572dd120)

As part of this diff I'm also deleting the method toSPFromPixel in favor of toDIPFromPixel because I noticed the usages of these methods are meant to use toDIPFromPixel()

changelog: [Internal] internal

Reviewed By: JoshuaGross

Differential Revision: D29864944

fbshipit-source-id: a0a093c120bde21a6cf9e1043a83c31e870d4368
2021-07-28 09:09:23 -07:00

59 lines
1.8 KiB
Java

/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.uimanager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
/** Android dp to pixel manipulation */
public class PixelUtil {
/** Convert from DIP to PX */
public static float toPixelFromDIP(float value) {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, value, DisplayMetricsHolder.getWindowDisplayMetrics());
}
/** Convert from DIP to PX */
public static float toPixelFromDIP(double value) {
return toPixelFromDIP((float) value);
}
/** Convert from SP to PX */
public static float toPixelFromSP(float value) {
return toPixelFromSP(value, Float.NaN);
}
/** Convert from SP to PX */
public static float toPixelFromSP(float value, float maxFontScale) {
DisplayMetrics displayMetrics = DisplayMetricsHolder.getWindowDisplayMetrics();
float scaledDensity = displayMetrics.scaledDensity;
float currentFontScale = scaledDensity / displayMetrics.density;
if (maxFontScale >= 1 && maxFontScale < currentFontScale) {
scaledDensity = displayMetrics.density * maxFontScale;
}
return value * scaledDensity;
}
/** Convert from SP to PX */
public static float toPixelFromSP(double value) {
return toPixelFromSP((float) value);
}
/** Convert from PX to DP */
public static float toDIPFromPixel(float value) {
return value / DisplayMetricsHolder.getWindowDisplayMetrics().density;
}
/** @return {@link float} that represents the density of the display metrics for device screen. */
public static float getDisplayMetricDensity() {
return DisplayMetricsHolder.getWindowDisplayMetrics().density;
}
}