systemInfo.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* eslint-disable import/no-mutable-exports */
  2. // 获取屏幕边界到安全区域距离
  3. let systemInfo
  4. let safeAreaInsets
  5. const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  6. // #ifdef MP-WEIXIN
  7. // 微信小程序使用新的API
  8. systemInfo = uni.getWindowInfo()
  9. safeAreaInsets = systemInfo.safeArea
  10. ? {
  11. top: systemInfo.safeArea.top,
  12. right: systemInfo.windowWidth - systemInfo.safeArea.right,
  13. bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
  14. left: systemInfo.safeArea.left,
  15. }
  16. : null
  17. // #endif
  18. // #ifndef MP-WEIXIN
  19. // 其他平台继续使用uni API
  20. systemInfo = uni.getSystemInfoSync()
  21. safeAreaInsets = systemInfo.safeAreaInsets
  22. // #endif
  23. console.log('systemInfo', systemInfo)
  24. // 微信里面打印
  25. // pixelRatio: 3
  26. // safeArea: {top: 47, left: 0, right: 390, bottom: 810, width: 390, …}
  27. // safeAreaInsets: {top: 47, left: 0, right: 0, bottom: 34}
  28. // screenHeight: 844
  29. // screenTop: 91
  30. // screenWidth: 390
  31. // statusBarHeight: 47
  32. // windowBottom: 0
  33. // windowHeight: 753
  34. // windowTop: 0
  35. // windowWidth: 390
  36. /**
  37. * 将 rpx 转换为 px
  38. * @param rpx rpx值
  39. * @returns px值
  40. */
  41. export function rpxToPx(rpx: number): number {
  42. // rpx基准是750rpx等于屏幕宽度
  43. const screenWidth = systemInfo?.windowWidth || 375 // 默认375px作为 fallback
  44. return (rpx * screenWidth) / 750
  45. }
  46. /**
  47. * 将 px 转换为 rpx
  48. * @param px px值
  49. * @returns rpx值
  50. */
  51. export function pxToRpx(px: number): number {
  52. // rpx基准是750rpx等于屏幕宽度
  53. const screenWidth = systemInfo?.windowWidth || 375 // 默认375px作为 fallback
  54. return (px * 750) / screenWidth
  55. }
  56. export { menuButtonInfo, safeAreaInsets, systemInfo }