react-native 自适应

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)
  }
  })
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值