React Native宽高适配问题

在React Native开发中,因为各种移动设备尺寸和分辨率的不同,造成尺寸无法统一设置,这就需要进行适配处理,一般的办法如下:

先定义常量保存开发时候手机模拟器的尺寸,如下是iPhone6s的尺寸:

/**
PixelRatio.get() === 1
    mdpi Android 设备 (160 dpi)
PixelRatio.get() === 1.5
    hdpi Android 设备 (240 dpi)
PixelRatio.get() === 2
    iPhone 4, 4S
    iPhone 5, 5c, 5s
    iPhone 6
    xhdpi Android 设备 (320 dpi)
    PixelRatio.get() === 3
    iPhone 6 plus
    xxhdpi Android 设备 (480 dpi)
PixelRatio.get() === 3.5
    Nexus 6
*/
import { Dimensions, PixelRatio } from 'react-native';
const BASE_WIN_HEIGHT = 667;
const BASE_WIN_WIDTH = 375;
const currentPixel = PixelRatio.get()  // 当前为iPhone6,值为2

然后写2个函数:

// 根据实际屏幕尺寸转换对应的像素高度

export function getHeight(h) {
    if (!this.height) {
          const {height, width} = Dimensions.get('window');
          this.height = height;
          this.width = width;
    }
      return h / currentPixel * (this.height / BASE_WIN_HEIGHT);
}

// 根据实际屏幕尺寸转换对应的像素宽度
export function getWidth(w) {
      if (!this.width) {
            const {height, width} = Dimensions.get('window');
            this.height = height;
            this.width = width;
      }
      return w / currentPixel * (this.width / BASE_WIN_WIDTH);
}

参数h和w是要设置组件的宽高的2倍值:
比如要设置按钮button的宽和高在iPhone6s中分别是100和30,那么在适配设置中调用上面的函数如下:

width: getWidth(200),
height: getHeight(60),

这样就能适配各种不同尺寸的移动设备了。

字体大小的适配,还是以iPhone 6尺寸为准
import { Dimensions, PixelRatio } from 'react-native';
const BASE_WIN_HEIGHT = 667;  // iPhone 6高度
const BASE_WIN_WIDTH = 375;    // iPhone 6宽度
const currentWidth = Dimensions.get('window').width;   // 当前设备宽度
const currentHeight = Dimensions.get('window').height;    // 当前设备高度
const pixelRatio = PixelRatio.get();      // 返回设备的像素密度
const pixelRatio6 = 2;      // 返回iPhone6的像素密度
const fontScale = PixelRatio.getFontScale();  // 字体大小缩放比例
const scale = Math.min(currentHeight / BASE_WIN_HEIGHT, currentWidth / BASE_WIN_WIDTH);

export function setText (val) {
    val = (val * scale) * pixelRatio / fontScale;
    return val / pixelRatio6;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容