import { Dimensions, PixelRatio, Platform, StatusBar } from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
const { width, height } = Dimensions.get('window');
import { getInset } from 'react-native-safe-area-view';
const landScape = width > height;
//Platform.OS === "android" ? StatusBar.currentHeight : 0
export const SAFE_TOP =
Platform.OS === 'android'
? StatusBar.currentHeight
: getInset('top', landScape);
export const SAFE_BOTTOM = getInset('bottom', landScape);
export const deviceWidth = Dimensions.get('window').width; //設備的寬度
export const deviceHeight = Dimensions.get('window').height; //設備的高度
let fontScale = PixelRatio.getFontScale(); //返回字體大小縮放比例
let pixelRatio = PixelRatio.get(); //當前設備的像素密度
let screenPxW = PixelRatio.getPixelSizeForLayoutSize(deviceWidth);
let screenPxH = PixelRatio.getPixelSizeForLayoutSize(deviceHeight);
const defaultPixel = 2; //iphone6的像素密度
//px轉換成dp
const w2 = Math.round(750 / defaultPixel);
const h2 = Math.round(1334 / defaultPixel);
const scale = Math.min(deviceHeight / h2, deviceWidth / w2); //獲取縮放比例
/**
* 設置text爲sp
* @param size sp
* @returns number dp
*/
export function setSpText(size) {
var scaleWidth = deviceWidth / 750;
var scaleHeight = deviceHeight / 1334;
var scale = Math.min(scaleWidth, scaleHeight);
size = Math.round((size * scale) / fontScale + 0.5);
return size;
}
/**
*
* @param size 元素的大小 類型爲數值類型
* @returns number dp
*/
export const scaleSize = function(size) {
if (size == 750) {
return deviceWidth;
}
size = Math.round(size * scale + 0.5) / defaultPixel;
return size;
};
export function scaleSizeW(size) {
var scaleWidth = (size * screenPxW) / 750;
size = Math.round(scaleWidth / pixelRatio + 0.5);
return size;
}
*/
使用eg:
主要使用scalew 設置寬高, setSpText 設置字體大小
原理就是根據屏幕寬度和設計度,等比縮放,類似rem
const styles = StyleSheet.create({
imgdesc:{
fontSize: setSpText(20),
color: "#999",
marginTop: scaleSizeW(16)
}
})