systemInfo.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // 其他平台提供默认值
  12. menuButtonInfo = null
  13. // #endif
  14. // #ifdef MP-WEIXIN
  15. // 微信小程序使用新的API
  16. systemInfo = uni.getWindowInfo()
  17. safeAreaInsets = systemInfo.safeArea
  18. ? {
  19. top: systemInfo.safeArea.top,
  20. right: systemInfo.windowWidth - systemInfo.safeArea.right,
  21. bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
  22. left: systemInfo.safeArea.left,
  23. }
  24. : null
  25. // #endif
  26. // #ifndef MP-WEIXIN
  27. // 其他平台继续使用uni API
  28. systemInfo = uni.getSystemInfoSync()
  29. safeAreaInsets = systemInfo.safeAreaInsets
  30. // #endif
  31. // console.log('systemInfo', systemInfo)
  32. // 微信里面打印
  33. // pixelRatio: 3
  34. // safeArea: {top: 47, left: 0, right: 390, bottom: 810, width: 390, …}
  35. // safeAreaInsets: {top: 47, left: 0, right: 0, bottom: 34}
  36. // screenHeight: 844
  37. // screenTop: 91
  38. // screenWidth: 390
  39. // statusBarHeight: 47
  40. // windowBottom: 0
  41. // windowHeight: 753
  42. // windowTop: 0
  43. // windowWidth: 390
  44. /**
  45. * 将 rpx 转换为 px
  46. * @param rpx rpx值
  47. * @returns px值
  48. */
  49. export function rpxToPx(rpx: number): number {
  50. // rpx基准是750rpx等于屏幕宽度
  51. const screenWidth = systemInfo?.windowWidth || 375 // 默认375px作为 fallback
  52. return (rpx * screenWidth) / 750
  53. }
  54. /**
  55. * 将 px 转换为 rpx
  56. * @param px px值
  57. * @returns rpx值
  58. */
  59. export function pxToRpx(px: number): number {
  60. // rpx基准是750rpx等于屏幕宽度
  61. const screenWidth = systemInfo?.windowWidth || 375 // 默认375px作为 fallback
  62. return (px * 750) / screenWidth
  63. }
  64. export { menuButtonInfo, safeAreaInsets, systemInfo }