JoJo的个人博客

记录精彩的程序人生

目录
Flutter屏幕适配
/  

Flutter屏幕适配

原理

比如 设计稿的分辨率是1080 * 1920,density为3,相当于360dp * 640dp

手机的分辨率是1440 * 2880,density为3.5,相当于411.4dp * 822.8dp

那么如果不进行适配的话,比如1080px的长度,在手机上将显示 1080/3.5= 308.6dp,比实际宽度要小很多

我们一般按照宽度来进行适配,即在当前示例,我们需要算出一个scale值,来让360dp变成411.4dp,这样才能撑满屏幕

首先 px = dp * density,不同设备的density值会不一样,ui稿设定density为3,按照360dp去写代码

那么 scale = (1440/3.5)/ (1080/3)

后面获取值的就直接用这个scale去乘就好了

附上代码

import 'dart:ui';

var S = new Screen();

///屏幕适配类
class Screen {
  /// 设计稿标准 1080 x 1920 像素
  double _normalWidth = 1080;
  double _normalHeight = 640;
  double _normalRatio = 3;

  /// 设备像素比
  double _devicePixelRatio;

  ///输出比例
  double scale;

  Screen._internal() {
    _devicePixelRatio = window.devicePixelRatio;
    scale = (window.physicalSize.width / _devicePixelRatio) /
        (_normalWidth / _normalRatio);

    print('window.physicalSize.width: ${window.physicalSize.width}');
    print('window.physicalSize.height: ${window.physicalSize.height}');
    print('window.devicePixelRatio: ${window.devicePixelRatio}');
    print('scale: $scale');
  }

  static Screen _singleton = new Screen._internal();

  factory Screen() => _singleton;

  double dp(double number) {
    return _singleton._dp(number);
  }

  _dp(double number) {
    return number * scale;
  }
}


标题:Flutter屏幕适配
作者:SunnySky
地址:https://www.tianyang.pub/articles/2020/07/02/1593675579839.html

评论