React Native宽高适配问题

作者: JokerPeng | 来源:发表于2016-12-30 13:21 被阅读4623次

在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;
}

相关文章

网友评论

  • 小哥奇葩:我想问下,那如果是字体和icon怎么随着屏幕适配呢,楼主有解决方案吗?
    小哥奇葩:@JokerPeng 嗯嗯我去下载了github 然后就可以了~谢谢楼主
    JokerPeng:你可以参照这篇文章 https://blog.csdn.net/u011272795/article/details/73824558,
    我在这篇文章基础上对自己的文章做了一些修改:blush:
    谢谢你的关注
  • 道灵:马
  • dd5f646cb35c:请问你这个对于屏幕宽高比不一样的情况该如何处理呢?
    JokerPeng:可能会影响到比例,比如按钮,输入框,但试过,影响不大

本文标题:React Native宽高适配问题

本文链接:https://www.haomeiwen.com/subject/vpsmvttx.html