flutter开发实战-获取屏幕显示大小及物理像素分辨率

flutter开发实战-获取屏幕显示大小及物理像素分辨率

在开发过程中,经常遇到需要获取屏幕显示的大小及物理像素分辨率,这里会用到MediaQuery,MediaQuery必须依赖BuildContext的上下文才能使用。

一、MediaQuery获取屏幕显示大小及物理像素分辨率

flutter中MediaQuery是一个用于获取设备屏幕信息的类。可以用它来获取屏幕宽度、高度、像素密度等信息,以便根据不同的屏幕尺寸进行适配。

例如

import 'package:flutter/material.dart';
 
void main() {
    
    
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
    
    
  
  Widget build(BuildContext context) {
    
    
    Size scrSize = MediaQuery.of(context).size;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MediaQuery示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '屏幕宽度:${
      
      scrSize.width}',
              ),
              Text(
                '屏幕高度:${
      
      scrSize.height}',
              ),
            ],
          ),
        ),
      ),
    );
  }
}

获取屏幕大小 (逻辑像素分辨率)

Size scrSize = MediaQuery.of(context).size;
double screenWidth = scrSize.width;
double screenHeight = scrSize.width;

获取到screenWidth与screenHeight,可要获取物理像素分辨率,我们还需要使用devicePixelRatio。
devicePixelRatio表示表示实际像素与逻辑像素的比例,为double类型。

获取方法

 double devicePixelRatio = MediaQuery.of(context).devicePixelRatio;

通过将屏幕的宽度和高度乘以设备像素比就可以得到物理像素分辨率

Size scrSize = MediaQuery.of(context).size;
    double screenWidth = scrSize.width;
    double screenHeight = scrSize.width;
 double devicePixelRatio = MediaQuery.of(context).devicePixelRatio;
double canvasWidth = screenWidth*devicePixelRatio;
double canvasHeight = screenHeight*devicePixelRatio;
  • 逻辑像素分辨率(Logical Pixel Resolution)
    逻辑像素分辨率是flutter中使用的抽象分辨率。它是与设备的无关的逻辑像素。代表可以通过程序控制使用的虚拟像素,是一个总体的概念。在逻辑像素分辨率下,屏幕的宽高是以逻辑像素进行度量测试的,不考虑实际的无力像素密度。以iphone7为例,手机逻辑分辨率375×667。

  • 物理像素分辨率(Physical Pixel Resolution)
    物理像素分辨率是实际物理设备上可用的像素分辨率,它根据设备的物理像素密度进行测量的。设备像素,或设备分辨率。以iphone7为例,手机分辨率750*1334。

  • 设备像素缩放比(Device Pixel Ratio)
    同一设备上也是固定的,表示设备物理像素与逻辑像素的比例。公式为:逻辑像素 * DPR = 物理像素。如iphone7的 DPR= 750/375 = 2

二、小结

flutter开发实战-获取屏幕显示大小及物理像素分辨率。

学习记录,每天不停进步。

猜你喜欢

转载自blog.csdn.net/gloryFlow/article/details/132504331