react-native开发react nativeReact Native开发经验集

React Native宽高适配问题

2016-12-30  本文已影响4623人  JokerPeng

在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;
}
上一篇 下一篇

猜你喜欢

热点阅读