react native 将设计稿中的像素值转换为设备独立像素值(dp)以适配不同设备
封装文件,将设计稿中的像素值转换为设备独立像素值(dp)。
首先,获取屏幕的宽度(screenWidth)和设计稿的宽度(uiWidth)。
然后,定义一个函数 pxToDp,它将设计稿中的像素值(uiElementPx)转换为设备独立像素值(dp)。计算公式为:
const dpValue = (uiElementPx * screenWidth) / uiWidth;
其中,uiElementPx 是设计稿中的像素值,screenWidth 是屏幕的宽度,uiWidth 是设计稿的宽度。通过这个计算,可以将设计稿中的像素值转换为适应当前屏幕的设备独立像素值。
import { Dimensions, StyleSheet } from "react-native"; const screenWidth = Dimensions.get("window").width; const uiWidth = 375; function pxToDp(uiElementPx) { return (uiElementPx * screenWidth) / uiWidth; } const adaptiveStyleSheet = { create(styles) { const transformedStyles = { ...styles }; const propertiesToAdapt = [ "width", "height", "marginTop", "marginRight", "marginBottom", "marginLeft", 'marginHorizontal', 'marginVertical', "paddingTop", "paddingRight", "paddingBottom", "paddingLeft", 'paddingHorizontal', 'paddingVertical', "top", "right", "bottom", "left", "fontSize", "lineHeight", ]; for (let key in transformedStyles) { const style = transformedStyles[key]; for (let property in style) { if ( propertiesToAdapt.includes(property) && typeof style[property] === "number" ) { style[property] = pxToDp(style[property]); } } } return StyleSheet.create(transformedStyles); }, }; export { adaptiveStyleSheet as StyleSheet, pxToDp };
使用
使用时直接按照设定的设计稿的尺寸书写样式(const uiWidth = 375;
)。
import { StyleSheet } from "./adaptiveStyleSheet"; const styles = StyleSheet.create({ container: { width: 200, // 在不同设备下会自动适配为设备独立像素 height: 100, marginTop: 10, fontSize: 16, }, }); export default styles;
行内使用
import { StyleSheet, pxToDp } from "./adaptiveStyleSheet"; <View style={{ width: pxToDp(200) }} />
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程