screen.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import 'package:flutter/material.dart';
  2. import 'package:get/get.dart';
  3. import 'package:trackoffical_app/styles/color_schemes.g.dart';
  4. class SizeFit{
  5. static double _screenWidth = 0;
  6. static double _screenHeight = 0;
  7. static double _screenWidthD = 0;
  8. static double _screenHeightD = 0;
  9. static double _rpx=0;
  10. static double _px=0;
  11. static const double standardWidth = 750;
  12. static void screenInit(BuildContext context){
  13. _screenWidthD = context.width;
  14. _screenHeightD = context.height;
  15. final physicalSize = View.of(context).physicalSize;
  16. // 获取物理分辨率
  17. var physicalWidth=physicalSize.width;
  18. var physicalHeight=physicalSize.height;
  19. //获取dpr
  20. var dpr=context.devicePixelRatio;
  21. _screenWidth = physicalWidth/dpr;
  22. _screenHeight = physicalHeight/dpr;
  23. // 计算rpx 和px大小
  24. _rpx = _screenWidth / standardWidth;
  25. _px = _screenWidth / standardWidth * 2; // 必须是乘以2,因为是以iphone6(750)为标准
  26. }
  27. // 按照像素来设置
  28. static double setPx(double size) {
  29. return _px * size ;
  30. }
  31. // 按照rpx来设置(如果给的设计稿是物理像素用rpx)
  32. static double setRpx(double size) {
  33. return _rpx * size;
  34. }
  35. }
  36. extension MNumFit on num {
  37. double get px {
  38. //这里的this是数字200.0, 相当于使用时 width: 200.0.px 里面的200.0 ,相当于是它调用方法
  39. return SizeFit.setPx(toDouble());
  40. }
  41. double get rpx {
  42. //这里和上面都是用的get ,所以外面使用的时候是:width:200.5.rpx
  43. return SizeFit.setRpx(toDouble());
  44. }
  45. /// 屏幕宽度百分比
  46. double get wp{
  47. return SizeFit._screenWidthD * (toDouble()/100);
  48. }
  49. /// 屏幕高度百分比
  50. double get hp{
  51. return SizeFit._screenHeightD * (toDouble()/100);
  52. }
  53. }
  54. class Preview extends StatelessWidget{
  55. const Preview({super.key, required this.child});
  56. final Widget child;
  57. @override
  58. Widget build(BuildContext context) {
  59. SizeFit.screenInit(context);
  60. return child;
  61. }
  62. }
  63. void runPreview(Widget child){
  64. runApp(GetMaterialApp(
  65. theme: ThemeData(useMaterial3: true, colorScheme: lightColorScheme),
  66. home: Preview(child: child)));
  67. }