分辨率适配系统 (Resolution Adaptation System)
本系统旨在解决 UniApp x 在不同设备分辨率下的精确样式适配和资源加载问题。通过预定义的配置对象,根据设备实际分辨率自动加载对应的样式值和图片资源,支持横竖屏自动切换及兜底机制。
1. 核心机制
系统基于 “配置对象 (Configuration Object)” 模式:
- 自动检测:App 启动或窗口调整时,自动获取屏幕宽高。
- 键值匹配:生成如
1024x768的 Key。 - 智能加载:
- 优先加载对应分辨率的专用配置(如
landscape/1024x768)。 - 未匹配则降级使用兜底配置(
landscape/common或portrait/common)。
- 优先加载对应分辨率的专用配置(如
- 响应式更新:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。
2. 目录结构
配置文件位于 config/resolution-adapt/:
config/resolution-adapt/
├── types/
│ └── index.uts # 【类型定义】定义所有页面配置的接口规范
├── index.uts # 【统一入口】聚合导出所有模块
├── core.uts # 【核心逻辑】updateResolutionConfig, getResponsiveImage
├── store.uts # 【状态管理】ResolutionState
├── adapter.uts # 【适配器】ResolutionAdapterImpl
├── hooks.uts # 【Hooks】useResponsiveImage
├── registry.uts # 【注册表】landscapeConfigs, portraitConfigs
├── landscape/ # 【横屏配置组】
│ ├── 1024x768/ # 特定分辨率目录
│ │ ├── demo.uts # Demo 页面专用配置
│ │ └── index.uts # 聚合导出
│ ├── 1920x1080/
│ └── common/ # 横屏兜底配置
└── portrait/ # 【竖屏配置组】
└── common/ # 竖屏兜底配置
3. 如何在页面中使用
3.1 页面模板 (Template)
使用全局组件 <Layout> 包裹页面内容,并使用全局属性 $resState 和 $getResImg。
<template>
<!-- 必须使用 Layout 包裹,它会自动注入 CSS 类名 -->
<Layout>
<!-- 方式 A: 根类名切换 (CSS) -->
<!-- Layout 组件会自动在根元素加上如 layout-landscape-1920x1080 的类名 -->
<view class="content">
<text class="title">Hello World</text>
</view>
<!-- 方式 B: JS 动态样式 (Style Binding) -->
<view class="dynamic-box"
:style="{ paddingLeft: $resState.config.demo.paddingLeft }">
<!-- 动态图片:使用全局方法 $getResImg 自动选择 @2x/@3x 图片 -->
<image :src="$getResImg($resState.config.demo.heroImageSrc)"
:style="{ width: $resState.config.demo.heroImageWidth }"
mode="widthFix" />
</view>
</Layout>
</template>
<script setup lang="uts">
// 无需 import 任何分辨率适配相关的代码!
</script>
<style scoped lang="scss">
// 引入拆分后的样式文件
@import "./styles/common.scss";
@import "./styles/landscape.scss";
@import "./styles/portrait.scss";
</style>
3.2 样式文件编写 (SCSS)
在 styles/landscape.scss 中利用根类名进行覆盖:
/* styles/landscape.scss */
.layout {
/* 针对 1920x1080 的覆盖样式 */
&.layout-landscape-1920x1080 {
.title {
font-size: 48rpx;
color: red;
}
}
/* 兜底样式 */
&.layout-landscape-common {
.title {
font-size: 32rpx;
color: blue;
}
}
}
4. 开发指南
4.1 定义图片资源 (ResponsiveImage)
系统强制要求图片资源配置必须包含 x1 路径,可选 x2, x3。
// types/index.uts
export type DemoPageConfig = {
heroImageSrc: ResponsiveImage // 使用 ResponsiveImage 类型
}
// landscape/common/demo.uts
heroImageSrc: {
x1: '/static/img/hero.png',
x2: '/static/img/hero@2x.png' // 编辑器会智能提示
}
4.2 添加新页面配置
假设要为 Home 页面添加适配:
定义接口: 在
types/index.uts中添加HomePageConfig并注册到AppResolutionConfig。实现配置: 在
landscape/common/,landscape/1024x768/等所有已注册的目录下创建home.uts。导出配置: 在各目录的
index.uts中导出新页面。
4.3 支持新的分辨率
假设需要支持 1280x800 分辨率:
- 创建目录:新建
config/resolution-adapt/landscape/1280x800/。 - 编写配置:复制
common下的文件到新目录并修改数值。 -
注册分辨率: 在
config/resolution-adapt/registry.uts中注册新目录。// config/resolution-adapt/registry.uts import { config as ls_1280 } from './landscape/1280x800/index.uts' const landscapeConfigs = { // ... "1280x800": ls_1280 // 新增 } as UTSJSONObject