screen_ruler.dart 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import 'package:flutter/material.dart';
  2. class ScreenRuler {
  3. static ScreenRuler _instance;
  4. ScreenRuler._internal();
  5. factory ScreenRuler.getInstance() => _instance;
  6. static const int defaultWidth = 750;
  7. //UI设计中手机尺寸 , px
  8. num uiWidthPx;
  9. //控制字体是否要根据系统的“字体大小”辅助选项来进行缩放。默认值为false。
  10. bool allowFontScaling;
  11. static double _screenWidth;
  12. static double _screenHeight;
  13. static double _pixelRatio;
  14. static double _statusBarHeight;
  15. static double _bottomBarHeight;
  16. static double _textScaleFactor;
  17. static void init(BuildContext context,
  18. {num width = defaultWidth, bool allowFontScaling = false}) {
  19. if (_instance == null) {
  20. _instance = ScreenRuler._internal();
  21. }
  22. _instance.uiWidthPx = width;
  23. _instance.allowFontScaling = allowFontScaling;
  24. MediaQueryData mediaQuery = MediaQuery.of(context);
  25. _pixelRatio = mediaQuery.devicePixelRatio;
  26. _screenWidth = mediaQuery.size.width;
  27. _screenHeight = mediaQuery.size.height;
  28. _statusBarHeight = mediaQuery.padding.top;
  29. _bottomBarHeight = mediaQuery.padding.bottom;
  30. _textScaleFactor = mediaQuery.textScaleFactor;
  31. }
  32. // 每个逻辑像素的字体像素数,字体的缩放比例
  33. static double get textScaleFactor => _textScaleFactor;
  34. // 设备的像素密度
  35. static double get pixelRatio => _pixelRatio;
  36. // 当前设备宽度 dp
  37. static double get screenWidth => _screenWidth;
  38. // 当前设备高度 dp
  39. static double get screenHeight => _screenHeight;
  40. // 当前设备宽度 px
  41. static double get screenWidthPx => _screenWidth * _pixelRatio;
  42. // 当前设备高度 px
  43. static double get screenHeightPx => _screenHeight * _pixelRatio;
  44. // 状态栏高度 dp 刘海屏会更高
  45. static double get statusBarHeight => _statusBarHeight;
  46. // 状态栏高度 dp 刘海屏会更高
  47. static double get statusBarHeightPx => _statusBarHeight * _pixelRatio;
  48. // 底部安全区距离 dp
  49. static double get bottomBarHeight => _bottomBarHeight;
  50. // 实际的dp与UI设计px的比例
  51. double get scale => screenWidth == 0 ? 0.5 : screenWidth / uiWidthPx;
  52. //根据UI设计的设备尺寸适配
  53. num compactDimenSize(num size) => size * scale;
  54. //根据UI设计的设备字体大小适配
  55. num compactScreenFontSize(num fontSize) => allowFontScaling
  56. ? (fontSize * scale)
  57. : ((fontSize * scale) / _textScaleFactor);
  58. }