systemInfo.ts 2.0 KB

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