React Native 屏幕适配

直接上代码

import { Dimensions,PixelRatio} from 'react-native';

export const windowWidth = Dimensions.get('window').width;    //当前设备宽高
export const windowHeight = Dimensions.get('window').height;  

const fontScale = PixelRatio.getFontScale();
const pixelRatio = PixelRatio.get();                //当前设备像素密度
const PPI = 2;                                      //iphone6 像素密度,将iPhone6作为基准
const iphone6Width = 750 / PPI;  
const iphone6Height = 1334 / PPI;
const scaleWidth = windowWidth / iphone6Width;        //获取宽高缩放比例
const scaleHeight = windowHeight / iphone6Height;     

/**
 * 设置text为sp
 * @param size  sp
 * @returns {Number} dp
 */
export function setSpText(size) {
    var scale = Math.min(scaleWidth, scaleHeight);
    size = Math.round((size * scale) * pixelRatio / fontScale);
    return size;
}

/**
 * 屏幕适配,缩放size
 * @param size
 * @returns {Number}
 * @constructor
 */
export function W(size) {
    size = Math.round((size * scaleWidth));
    return size / PPI;
}

export function H(size) {
    size = Math.round((size * scaleHeight));
    return size / PPI;
}
/*
*根据屏幕分辨率设置百分比
*/
export function HB(length){
    let dp = Math.round(windowHeight * ( length / 100 ));
    return dp;
}

export function WB(length){
    let dp = Math.round(windowWidth * ( length / 100 ));
    return dp;
}

默认以iPhone6 宽高为基准。

用法

比如iPhone6 宽度为 1334
如果在iPhone6上设置宽度为一半。 那么就是 1334 / 2 = 667

直接 W(667) 就可算出对应的设备缩放后的 宽度了

宽度为W 函数,高度 H 函数,
百分比宽高为 WB,HB,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值