import { Dimensions, PixelRatio, Platform, StatusBar } from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';

const { width, height } = Dimensions.get('window');
import { getInset } from 'react-native-safe-area-view';
const landScape = width > height;
//Platform.OS === "android" ? StatusBar.currentHeight : 0

export const SAFE_TOP =
  Platform.OS === 'android'
    ? StatusBar.currentHeight
    : getInset('top', landScape);
export const SAFE_BOTTOM = getInset('bottom', landScape);

export const deviceWidth = Dimensions.get('window').width; //设备的宽度
export const deviceHeight = Dimensions.get('window').height; //设备的高度
let fontScale = PixelRatio.getFontScale(); //返回字体大小缩放比例

let pixelRatio = PixelRatio.get(); //当前设备的像素密度
let screenPxW = PixelRatio.getPixelSizeForLayoutSize(deviceWidth);
let screenPxH = PixelRatio.getPixelSizeForLayoutSize(deviceHeight);

const defaultPixel = 2; //iphone6的像素密度
//px转换成dp
const w2 = Math.round(750 / defaultPixel);
const h2 = Math.round(1334 / defaultPixel);
const scale = Math.min(deviceHeight / h2, deviceWidth / w2); //获取缩放比例
/**
 * 设置text为sp
 * @param size sp
 * @returns number dp
 */
export function setSpText(size) {
  var scaleWidth = deviceWidth / 750;
  var scaleHeight = deviceHeight / 1334;
  var scale = Math.min(scaleWidth, scaleHeight);
  size = Math.round((size * scale) / fontScale + 0.5);
  return size;
}

/**
 *
 * @param size 元素的大小 类型为数值类型
 * @returns number dp
 */
export const scaleSize = function(size) {
  if (size == 750) {
    return deviceWidth;
  }
  size = Math.round(size * scale + 0.5) / defaultPixel;
  return size;
};
export function scaleSizeW(size) {
  var scaleWidth = (size * screenPxW) / 750;
  size = Math.round(scaleWidth / pixelRatio + 0.5);
  return size;
}
 */

使用eg:
主要使用scalew 设置宽高, setSpText 设置字体大小
原理就是根据屏幕宽度和设计度,等比缩放,类似rem

const styles = StyleSheet.create({
  imgdesc:{
    fontSize: setSpText(20),
    color: "#999",
    marginTop: scaleSizeW(16)
  }
  })
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐