Flutter开发:手机屏幕适配(自适应)方案

2019-03-1808:14:41WEB前端开发Comments13,311 views3字数 1197阅读模式

手机屏幕尺寸各不相同,导致我们平时写布局的时候会在个不同的移动设备上显示的效果不同。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

为了达到一套代码所有手机体验一致效果,需要做尺寸上的适配。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

适配方案:

计算公式:实际尺寸 = UI尺寸 * 设备宽度/设计图宽度文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

1px方案 : 1px = 1 / 设备像素比文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

实现代码如下(以750设计图为例):

import 'package:flutter/material.dart';
import 'dart:ui';

class Adapt {
    static MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);
    static double _width = mediaQuery.size.width;
    static double _height = mediaQuery.size.height;
    static double _topbarH = mediaQuery.padding.top;
    static double _botbarH = mediaQuery.padding.bottom;
    static double _pixelRatio = mediaQuery.devicePixelRatio;
    static var _ratio;
    static init(int number){
        int uiwidth = number is int ? number : 750;
        _ratio = _width / uiwidth;
    }
    static px(number){
        if(!(_ratio is double || _ratio is int)){Adapt.init(750);}
        return number * _ratio;
    }
    static onepx(){
        return 1/_pixelRatio;
    }
    static screenW(){
        return _width;
    }
    static screenH(){
        return _height;
    }
    static padTopH(){
        return _topbarH;
    }
    static padBotH(){
        return _botbarH;
    }
}

解析:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

1、默认750设计图文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

2、引入 'dart:ui' 获得屏幕尺寸相关信息文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

3、计算真实像素值文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html

使用方式:

// 设置文本大小 30 为设计图尺寸
new Text(
    'Hello World!',
    style: TextStyle(
         fontSize: Adapt.px(30),
     )
)
// 容器尺寸大小设置 一个设计图为 300*300像素的容器
new Container(    width: Adapt.px(300),  
    height: Adapt.px(300),
)
// 1px 
new Container(
    decoration: new BoxDecoration(
          border: new Border(bottom:BorderSide(width: Adapt.one())),
    ),
)
  • Adapt.px(100)  计算适配后的尺寸
  • Adapt.onepx()  1px像素大小
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10123.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/10123.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定