Flutter桌面应用如何进行多分辨率适配
通过此篇文章,你将了解到:
Flutter windows和Android桌面应用屏幕适配的解决方案;屏幕适配的相关知识和原理;flutter_screenutil的实现原理和缺陷。??本文为稀土掘金技术社区首发签约文章,14天内禁止转载,14天后未获授权禁止转载,侵权必究!
前言Flutter桌面应用的开发过程中,势必需要适配不同尺寸的屏幕。我们的预期是在不同尺寸的设备上,用户的使用感观基本一致。如:在个人pc上,应用与屏幕的高度比是2/3;那么到60寸的大设备上,应用的尺寸依然需要2/3比例。
屏幕适配的一些基础概念屏幕尺寸:屏幕的实际大小,主要看屏幕的对角线的长度,如:6.6英寸。分辨率:屏幕上像素点的总和,如:2400×1176。设备的屏幕其实是由N个像素格子组合成的,屏幕上显示的所有元素(图片、文字)从微观上都是为特定的像素格子绘制上内容。屏幕密度(dpi):每英寸的像素格子数。每英寸展示160个像素时称为一倍素;120个称为低倍素...假设我们需要展示一张800×800的图片,那么在160dpi的手机屏幕上,我们只要设置800×800px的宽高;但在320dpi的屏幕上,由于每英寸的像素点翻倍了,为了用户的视觉感受一致,就需要将图片设置的宽高设为1600×1600px。这就是屏幕适配最基本的原理,我们开发中所用到的适配库,最基础的能力就是提供这层转换。
Flutter 移动端开发的通用做法Flutter移动端的生态已经很完备,我们一般在开发过程中会使用flutter_screenutil这个插件。这是一个纯Dart的pub,阅读源码发现其做法也很简单粗暴。
根据传入的设计稿尺寸,与设备的逻辑像素尺寸的比值作为缩放倍数;开发者设置的尺寸都会去乘以对应的缩放倍数,从而实现widget大小的转换。extensionSizeExtensiononnum{
///[ScreenUtil.setWidth]
doublegetw=ScreenUtil().setWidth(this);
///[ScreenUtil.setHeight]
doublegeth=ScreenUtil().setHeight(this);
......
)
doublegetscreenHeight=
_context!=null?MediaQuery.of(_context!).size.height:_screenHeight;
doublesetHeight(numheight)=height*scaleHeight;
//高度的缩放比:设备的逻辑像素的高度/设计稿的高度
doublegetscaleHeight=
(_splitScreenMode?max(screenHeight,700):screenHeight)/
_uiSize.height;
逻辑像素screenHeight从哪来?
获取MediaQueryData的size,即应用窗口的分辨率。extensiononMediaQueryData?{
MediaQueryData?nonEmptySizeOrNull(){
if(this?.size.isEmpty??true)
returnnull;
else
returnthis;
}
}
///Thesizeofthemediainlogicalpixels(e.g,thesizeofthescreen).
///
///Logicalpixelsareroughlythesamevisualsizeacrossdevices.Physical
///pixelsarethesizeoftheactualhardwarepixelsonthedevice.The
///numberofphysicalpixelsperlogicalpixelisdescribedbythe
///[devicePixelRatio].
finalSizesize;
存在的问题flutter_screenutil 这个库在移动端使用是完全没有问题的。手机尺寸虽说层出不穷,但是也遵循瘦长的长方形规则,最重要的是应用默认都是全屏的,那么上面第3点获取到的应用窗口高度screenHeight和设备的大小刚好是完全吻合的。从而计算出的缩放比(设计稿尺寸/设备的尺寸 = 缩放比值)是偏差不大的。
我们在Android的桌面应用中,这个库也可以支持各种设备。
然而在windows等桌面端却没那么简单:
首先桌面设备的尺寸层出不穷,从个人笔记本到演示厅的屏幕,物理大小就已经差了几十倍,而像素密度却差别不大,这在适配上本身就存在更大难度。且通过验证,FlutterMediaQueryData获取的是应用窗口的大小,但是桌面设备屏幕大小跟应用窗口大小可不是一样大的,这就是最大的问题所在!
通过实践我们也验证了flutter_screenutil在桌面端的适配基本不起作用,且还会造成不少问题,比如:第一次运行字体都会偏大;当有多个扩展屏的时候,主副屏切换有bug。
桌面端解决方案一、需求分析我们希望flutter开发出来的应用,在不同的设备中:
应用的大小占比屏幕物理尺寸的比例是一致的;系统显示设置中的的缩放倍数不会影响应用的大小;资源大小可以进行适配,让图片等资源在不同尺寸的设备上都能显示清晰。分析以上预期效果,可以提炼出一个原则:**应用的尺寸必须跟屏幕的物理大小占比一致,与分辨率、像素密度、缩放比都没关系。**
二、实现原理由于Android端用了flutter_screenutil这个库,Flutter又是跨平台的。为了降低开发成本,我试着fork源码下来更改,并且做了以下的操作:
在构造函数上,我加了一个参数app2screenWithWidth,让用户告知应用窗口宽度与屏幕宽度的比值,如:70%传入0.7;//文件路径:flutter_screenutil/lib/src/screenutil_init.dart
classScreenUtilInitextendsStatefulWidget{
///Ahelperwidgetthatinitializes[ScreenUtil]
constScreenUtilInit({
Key?key,
requiredthis.builder,
this.child,
this.rebuildFactor=RebuildFactors.size,
this.designSize=ScreenUtil.defaultSize,
this.app2screenWithWidth=1,
this.splitScreenMode=false,
this.minTextAdapt=false,
this.useInheritedMediaQuery=false,
}):super(key:key);
finalScreenUtilInitBuilderbuilder;
finalWidget?child;
finalboolsplitScreenMode;
finalboolminTextAdapt;
finalbooluseInheritedMediaQuery;
finalRebuildFactorrebuildFactor;
///The[Size]ofthedeviceinthedesigndraft,indp
finalSizedesignSize;
///适用于桌面应用,应用窗口宽度与设备屏幕宽度的比例
finaldoubleapp2screenWithWidth;
@override
StateScreenUtilInitcreateState()=_ScreenUtilInitState();
}
yaml中引入screenRetriever,获取到真实的设备屏幕像素,这个是真实的屏幕像素,跟应用窗口没关系;然后可以计算出应用窗口的大小,得出转换系数;dependencies:
flutter:
sdk:flutter
#获取屏幕物理参数
screen_retriever:^0.1.2
//文件路径:flutter_screenutil/lib/src/screen_util.dart
///Initializingthelibrary.
staticFuturevoidinit(
BuildContextcontext,{
SizedesignSize=defaultSize,
doubleapp2screenWithWidth=1,
boolsplitScreenMode=false,
boolminTextAdapt=false,
})async{
finalnavigatorContext=Navigator.maybeOf(context)?.contextasElement?;
finalmediaQueryContext=
navigatorContext?.getElementForInheritedWidgetOfExactTypeMediaQuery
finalinitCompleter=Completervoid
WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_){
mediaQueryContext?.visitChildElements((el)=_instance._context=
if(_instance._context!=null)initCompleter.complete();
//**我修改的代码**
Orientationorientation=Orientation.landscape;
SizedeviceSize=Size.zero;
if(isDesktop){
DisplayprimaryDisplay=awaitscreenRetriever.getPrimaryDisplay();
deviceSize=primaryDisplay.size;
orientation=deviceSize.widthdeviceSize.height
?Orientation.landscape
:Orientation.portrait;
}else{
finaldeviceData=MediaQuery.maybeOf(context).nonEmptySizeOrNull();
deviceSize=deviceData?.size??designSize;
orientation=deviceData?.orientation??
(deviceSize.widthdeviceSize.height
?Orientation.landscape
:Orientation.portrait);
}
_instance
.._context=context
.._uiSize=designSize
.._splitScreenMode=splitScreenMode
.._minTextAdapt=minTextAdapt
.._orientation=orientation
.._screenWidth=deviceSize.width
.._screenHeight=deviceSize.height;
//桌面区分设置下窗口大小
if(isDesktop){
doubleappWidth=deviceSize.width*app2screenWithWidth;
doubleappHeight=appWidth/(designSize.width/designSize.height);
_instance._uiSize=Size(appWidth,appHeight);
}
_instance._elementsToRebuild?.forEach((el)=el.markNeedsBuild());
returninitCompleter.future;
}
之后setWidth等方法都不需要懂了,因为都是拿上面的转换系数去计算的,系数对了转换自然就准确了。同时开发过程中也不需要做任何区分,该用.w的就用.w。我们看下.w等是如何通过扩展巧妙的把setWidth这些接口做的轻量的。extensionSizeExtensiononnum{
///[ScreenUtil.setWidth]
doublegetw=ScreenUtil().setWidth(this);
///[ScreenUtil.setHeight]
doublegeth=ScreenUtil().setHeight(this);
///[ScreenUtil.radius]
doublegetr=ScreenUtil().radius(this);
///[ScreenUtil.setSp]
doublegetsp=ScreenUtil().setSp(this);
///smartsize:itcheckyourvalue-ifitisbiggerthanyourvalueitwillsetyourvalue
///forexample,youhaveset16.sm(),ifforyourscreen16.sp()isbiggerthan16,thenitwillset16not16.sp()
///Ithinkthatitisgoodforsavesizebalanceonbigsizesofscreen
doublegetsm=min(toDouble(),
///屏幕宽度的倍数
///Multipleofscreenwidth
doublegetsw=ScreenUtil().screenWidth*this;
///屏幕高度的倍数
///Multipleofscreenheight
doublegetsh=ScreenUtil().screenHeight*this;
///[ScreenUtil.setHeight]
WidgetgetverticalSpace=ScreenUtil().setVerticalSpacing(this);
///[ScreenUtil.setVerticalSpacingFromWidth]
WidgetgetverticalSpaceFromWidth=
ScreenUtil().setVerticalSpacingFromWidth(this);
///[ScreenUtil.setWidth]
WidgetgethorizontalSpace=ScreenUtil().setHorizontalSpacing(this);
///[ScreenUtil.radius]
WidgetgethorizontalSpaceRadius=
ScreenUtil().setHorizontalSpacingRadius(this);
///[ScreenUtil.radius]
WidgetgetverticalSpacingRadius=
ScreenUtil().setVerticalSpacingRadius(this);
}
资源适配,定义三个设备类型:大、中、小级别;然后在asset目录下区分三套资源,命名规范区分下larger、medium、small即可。
这个做法非常硬核,我目前也没这个需求(O(∩_∩)O~。后续考虑渠道编译,减少包体积,同时开发时也不用区分名称。写在最后以上方案,我在demo项目中验证过是没有问题的。接下来我希望能跟作者沟通下这个方案,看能否提pr合并进去。不然以后就没办法很轻松的享受到flutter_screenutil的更新迭代了。
期待Flutter桌面社区越来越丰富
阅读原文
网站开发网络凭借多年的网站建设经验,坚持以“帮助中小企业实现网络营销化”为宗旨,累计为4000多家客户提供品质建站服务,得到了客户的一致好评。如果您有网站建设、网站改版、域名注册、主机空间、手机网站建设、网站备案等方面的需求...
请立即点击咨询我们或拨打咨询热线:13245491521 13245491521 ,我们会详细为你一一解答你心中的疑难。 项目经理在线