flutter_screenutil.dart 2.8 KB
Newer Older
L
li_zy 已提交
1
/*
李卓原 已提交
2
 * Created by 李卓原 on 2018/9/29.
李卓原 已提交
3 4 5
 * email: zhuoyuan93@gmail.com
 */

李卓原 已提交
6
import 'package:flutter/material.dart';
李卓原 已提交
7 8

class ScreenUtil {
李卓原 已提交
9
  static ScreenUtil instance = new ScreenUtil();
L
li_zy 已提交
10 11

  //设计稿的设备尺寸修改
李卓原 已提交
12 13 14 15 16 17 18 19 20 21
  int _designWidth;
  int _designHeight;

  static MediaQueryData _mediaQueryData;
  static double _screenWidth;
  static double _screenHeight;
  static double _pixelRatio;
  static double _statusBarHeight;

  static double _bottomBarHeight;
李卓原 已提交
22

李卓原 已提交
23 24
  static double _textScaleFactor;

李卓原 已提交
25
  ScreenUtil({int width, int height}) {
李卓原 已提交
26 27
    _designWidth = width;
    _designHeight = height;
李卓原 已提交
28 29 30 31 32 33
  }

  static ScreenUtil getInstance() {
    return instance;
  }

李卓原 已提交
34 35 36 37 38 39 40 41
  void init(BuildContext context) {
    MediaQueryData mediaQuery = MediaQuery.of(context);
    _mediaQueryData = mediaQuery;
    _pixelRatio = mediaQuery.devicePixelRatio;
    _screenWidth = mediaQuery.size.width;
    _screenHeight = mediaQuery.size.height;
    _statusBarHeight = mediaQuery.padding.top;
    _bottomBarHeight = _mediaQueryData.padding.bottom;
李卓原 已提交
42
    _textScaleFactor = mediaQuery.textScaleFactor;
李卓原 已提交
43 44 45 46
  }

  static MediaQueryData get mediaQueryData => _mediaQueryData;

李卓原 已提交
47 48 49
  ///每个逻辑像素的字体像素数,字体的缩放比例
  static double get textScaleFactory => _textScaleFactor;

李卓原 已提交
50 51
  ///设备的像素密度
  static double get pixelRatio => _pixelRatio;
李卓原 已提交
52

李卓原 已提交
53 54
  ///当前设备宽度 px
  static double get screenWidth => _screenWidth * _pixelRatio;
李卓原 已提交
55

李卓原 已提交
56 57
  ///当前设备高度 px
  static double get screenHeight => _screenHeight * _pixelRatio;
李卓原 已提交
58

李卓原 已提交
59 60
  ///状态栏高度 刘海屏会更高
  static double get statusBarHeight => _statusBarHeight * _pixelRatio;
李卓原 已提交
61

李卓原 已提交
62 63
  ///底部安全区距离
  static double get bottomBarHeight => _bottomBarHeight * _pixelRatio;
李卓原 已提交
64

李卓原 已提交
65
  ///实际的dp与设计稿px的比例
李卓原 已提交
66
  get scaleWidth => _screenWidth / instance._designWidth;
李卓原 已提交
67

李卓原 已提交
68
  get scaleHeight => _screenHeight / instance._designHeight;
李卓原 已提交
69

李卓原 已提交
70 71
  ///根据设计稿的设备宽度适配
  ///高度也根据这个来做适配可以保证不变形
李卓原 已提交
72 73
  setWidth(int width) => width * scaleWidth;

李卓原 已提交
74 75 76 77
  /// 根据设计稿的设备高度适配
  /// 当发现设计稿中的一屏显示的与当前样式效果不符合时,
  /// 或者形状有差异时,高度适配建议使用此方法
  /// 高度适配主要针对想根据设计稿的一屏展示一样的效果
李卓原 已提交
78
  setHeight(int height) => height * scaleHeight;
李卓原 已提交
79 80 81 82 83 84

  ///字体大小适配方法
  ///@param fontSize 传入设计稿上字体的px ,
  ///@param allowFontScaling 控制字体是否要根据系统的“字体大小”辅助选项来进行缩放。默认值为true。
  ///@param allowFontScaling Specifies whether fonts should scale to respect Text Size accessibility settings. The default is true.
  setSp(int fontSize, [allowFontScaling = true]) => allowFontScaling
李卓原 已提交
85 86
      ? setWidth(fontSize) * _textScaleFactor
      : setWidth(fontSize);
李卓原 已提交
87
}