「React Native」UI适配

2020-05-22  本文已影响0人  七月流火_9405

一、按比例对UI切图进行转化。

import { Dimensions, Platform } from 'react-native';
export const WIDTH = Dimensions.get('window').width;
export const HEIGHT = Dimensions.get('window').height;
export const isIOS = (Platform.OS === 'ios');//系统是iOS
// 设计图上的比例,宽度
let basePx = 360;
const deviceW = Dimensions.get('window').width;
/**
 * 适配宽高
 * @param {width、height} px 
 */
export function px2dp(px) {
  return px * deviceW / basePx;
}

/**
 * 适配字体
 * @param {width、height} px 
 */
export function px2sp(px) {
  return px * deviceW / basePx;
}

//iPhone X
const X_SCREEN_WIDTH = 375;
const X_SCREEN_HEIGHT = 812;

export function isIphoneX() {
  return (
    Platform.OS === 'ios' && ((X_SCREEN_WIDTH === WIDTH && X_SCREEN_HEIGHT === HEIGHT)
      || (X_SCREEN_WIDTH === HEIGHT && X_SCREEN_HEIGHT === WIDTH)
    )
  );
}

export default {
  WIDTH,
  HEIGHT,
  isIOS,
  isIphoneX,
  px2dp,
  px2sp
}

二、动态赋值

import Adapt, { px2dp, px2sp } from '../commons/Adapt'
import { StyleSheet } from 'react-native';

export default class StylesUtil {
    protected px2dp = px2dp
    protected px2sp = px2sp
    protected Adapt = Adapt

    static create<T extends StyleSheet.NamedStyles<T> | StyleSheet.NamedStyles<any>>(obj: T): T {
        this.updateSource(obj)
        //console.log("尺寸变化后:", obj);
        return StyleSheet.create(obj)
    }

    static updateSource(source) {
        Object.keys(source).forEach(k => {
            //console.log('开始遍历key:', k);
            //console.log('开始遍历value:', source[k]);
            //如果值是对象则继续遍历
            if (typeof source[k] === 'object') {
                this.updateSource(source[k])
            } else {
                if (typeof source[k] === 'number') {//只替换值类型为数字的情况
                    if (k === 'fontSize') {//如果是字体大小就转换为sp
                        source[k] = px2sp(source[k])
                    } else if (k === 'flex') {//如果是flex,则不做处理。 
                    } else if (k.indexOf('border') != -1) {//如果是border,则不做处理。
                    } else if (source[k] !== StyleSheet.hairlineWidth) {//如果是hairlineWidth,则不做处理。
                    } else {//否则转换为dp单位
                        source[k] = px2dp(source[k])
                    }
                }
            }
        })
    }

}
上一篇 下一篇

猜你喜欢

热点阅读