我们正在开发一款应用,它将在多个设备(iOS、Android)上运行,因此要适应许多不同的屏幕尺寸。在阅读了PixelRatio之后,似乎没有一个神奇的解决方案可以自动缩放所有样式值来适应不同的屏幕尺寸。
我所能想到的唯一解决方案是重写
我所能想到的唯一解决方案是重写
Stylesheet
类,自动根据当前屏幕尺寸缩放所有大小,例如:import {StyleSheet} from ‘react-native’;
import { Dimensions, Platform, PixelRatio } from ‘react-native’;
const {
width,
height
} = Dimensions.get(‘window’);
const scale = width / 320;
const ratioKeys = {
fontSize: true,
paddingHorizontal: true,
paddingVertical: true,
paddingTop: true,
paddingLeft: true,
paddingRight: true,
paddingBottom: true,
padding: true,
marginHorizontal: true,
marginVertical: true,
marginTop: true,
marginRight: true,
marginLeft: true,
marginBottom: true,
margin: true,
width: true,
height: true,
lineHeight: true,
}
// automatically scale specific keys (specified above) according to the screen size
const parseKey = (key, value) => {
if (ratioKeys[key]) {
value = value * scale;
}
return value;
}
export const parseStyle = (style) => {
console.log(‘style -> ’, style);
return Object.keys(style).reduce((output, key) => {
output[key] = parseKey(key, style[key]);
return output;
}, {});
}
const parseStyleSheet = (styles) => {
console.log(‘styles -> ’, styles);
return Object.keys(styles).reduce((output, key) => {
output[key] = parseStyle(styles[key]);
return output;
}, {});
}
export default {
create: (style) => {
return StyleSheet.create(parseStyleSheet(style));
}
}
看起来这样做不会自动支持,所以我猜我错过了什么?