Commit 4b3a8d00 by liimin

feat: 添加分辨率适配系统并重构登录页面样式

- 新增分辨率适配系统,包含配置注册表、适配器、状态管理和核心逻辑
- 添加横竖屏及特定分辨率(1174x768、1920x1080)的样式配置
- 创建 Layout 全局组件,自动注入分辨率相关的 CSS 类名
- 重构登录页面样式,拆分为通用、横屏和竖屏样式文件
- 在 App 启动时初始化分辨率配置,并在全局挂载响应式图片处理函数
- 更新 pages.json 添加 Layout 组件注册
1 parent 0824a866
Showing 26 changed files with 734 additions and 3 deletions
<script lang="uts"> <script lang="uts">
import { updateResolutionConfig } from "@/config/resolution-adapt/index.uts";
// #ifdef APP // #ifdef APP
import { layoutService } from "@/services/LayoutService.uts"; import { layoutService } from "@/services/LayoutService.uts";
import { recordService } from "@/services/recorder"; import { recordService } from "@/services/recorder";
...@@ -10,6 +11,10 @@ export default { ...@@ -10,6 +11,10 @@ export default {
onLaunch () { onLaunch () {
// #ifdef APP // #ifdef APP
layoutService.init(); layoutService.init();
// uni.onWindowResize((res) => {
// updateResolutionConfig();
// });
// #endif // #endif
console.log("App Launch"); console.log("App Launch");
...@@ -22,6 +27,7 @@ export default { ...@@ -22,6 +27,7 @@ export default {
setTimeout(() => { setTimeout(() => {
recordService.stopAudio(); recordService.stopAudio();
}, 10_000); }, 10_000);
updateResolutionConfig();
}, 1000); }, 1000);
}, },
onShow () { onShow () {
......
<template>
<view class="layout-root" :class="[resolutionState.cssClass]">
<slot />
</view>
</template>
<script setup lang="uts">
import { resolutionState, useResolutionConfig } from "@/config/resolution-adapt/index.uts";
// 在这里统一调用初始化,确保任何使用 Layout 的页面都能获得正确的配置
useResolutionConfig();
</script>
<style scoped>
.layout-root {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
</style>
# 分辨率适配系统 (Resolution Adaptation System)
本系统旨在解决 UniApp x 在不同设备分辨率下的精确样式适配和资源加载问题。通过预定义的配置对象,根据设备实际分辨率自动加载对应的样式值和图片资源,支持横竖屏自动切换及兜底机制。
## 1. 核心机制
系统基于 **“配置对象 (Configuration Object)”** 模式:
1. **自动检测**:App 启动或窗口调整时,自动获取屏幕宽高。
2. **键值匹配**:生成如 `1024x768` 的 Key。
3. **智能加载**:
* 优先加载对应分辨率的专用配置(如 `landscape/1024x768`)。
* 未匹配则降级使用兜底配置(`landscape/common` 或 `portrait/common`)。
4. **响应式更新**:配置对象是 Vue Reactive 的,分辨率变化时页面自动更新。
## 2. 目录结构
配置文件位于 `config/resolution-adapt/`:
```text
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`。
```html
<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` 中利用根类名进行覆盖:
```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`。
```typescript
// 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` 页面添加适配:
1. **定义接口**:
在 `types/index.uts` 中添加 `HomePageConfig` 并注册到 `AppResolutionConfig`。
2. **实现配置**:
在 `landscape/common/`, `landscape/1024x768/` 等所有已注册的目录下创建 `home.uts`。
3. **导出配置**:
在各目录的 `index.uts` 中导出新页面。
### 4.3 支持新的分辨率
假设需要支持 `1280x800` 分辨率:
1. **创建目录**:新建 `config/resolution-adapt/landscape/1280x800/`。
2. **编写配置**:复制 `common` 下的文件到新目录并修改数值。
3. **注册分辨率**:
在 `config/resolution-adapt/registry.uts` 中注册新目录。
```typescript
// config/resolution-adapt/registry.uts
import { config as ls_1280 } from './landscape/1280x800/index.uts'
const landscapeConfigs = {
// ...
"1280x800": ls_1280 // 新增
} as UTSJSONObject
```
import { landscapeMap, portraitMap } from "./registry.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 4. 适配器定义 (Adapter Definition)
// ========================================================================
export interface IResolutionAdapter {
match(w: number, h: number): boolean
getConfig(key: string): AppResolutionConfig | null
getFallback(): AppResolutionConfig | null
getPrefix(): string
getCssClass(key: string): string
}
class ResolutionAdapterImpl implements IResolutionAdapter {
private map: Map<string, AppResolutionConfig>;
private matcher: (w: number, h: number) => boolean;
private prefix: string;
constructor(prefix: string, map: Map<string, AppResolutionConfig>, matcher: (w: number, h: number) => boolean) {
this.prefix = prefix;
this.map = map;
this.matcher = matcher;
}
getConfig(key: string): AppResolutionConfig | null { return this.map.get(key); }
getCssClass(key: string): string {
// 生成 CSS 类名规则:layout-{prefix}-{width}x{height}
// 例如:layout-landscape-1920x1080
// 如果未匹配到具体分辨率,使用 layout-{prefix}-common
if (this.map.has(key)) {
return `layout-${this.prefix}-${key}`;
}
return `layout-${this.prefix}-common`;
}
getFallback(): AppResolutionConfig | null { return this.map.get("common"); }
getPrefix(): string { return this.prefix; }
match(w: number, h: number): boolean { return this.matcher(w, h); }
}
export const resolutionAdapters: IResolutionAdapter[] = [
new ResolutionAdapterImpl("landscape", landscapeMap, (w, h) => w > h),
new ResolutionAdapterImpl("portrait", portraitMap, (w, h) => w <= h)
];
import { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
import { initRegistry, isRegistryInitialized } from "./registry.uts";
import { resolutionState } from "./store.uts";
import { AppResolutionConfig, ResponsiveImage } from "./types/index.uts";
// ========================================================================
// 5. 核心适配逻辑 (Core Logic)
// ========================================================================
export function updateResolutionConfig() {
initRegistry();
const info = uni.getWindowInfo();
console.log("🚀 ~ updateResolutionConfig ~ info:", info);
// 优先取 windowWidth,如果为 0 则取 screenWidth (物理屏幕宽)
let w = info.windowWidth;
let h = info.windowHeight;
const pr = info.pixelRatio;
// 兜底逻辑...
if (w === 0 && info.screenWidth > 0) {
w = info.screenWidth;
if (info.screenHeight > 0) h = info.screenHeight;
console.warn(`[ResolutionAdapt] windowWidth is 0, fallback to screenWidth: ${w}x${h}`);
}
if (w === 0 || h === 0) {
console.error(`[ResolutionAdapt] Failed to get valid window size: ${w}x${h}`);
return;
}
const key = `${Math.round(w)}x${Math.round(h)}`;
console.log(`[ResolutionAdapt] Window: ${w}x${h} @${pr}x, Key: ${key}`);
// 使用适配器模式匹配
let adapter: IResolutionAdapter | null = null;
for (const a of resolutionAdapters) {
if (a.match(w, h)) {
adapter = a;
break;
}
}
if (adapter === null) {
console.error(`[ResolutionAdapt] No adapter matched for ${w}x${h}`);
return;
}
// 执行适配
let target = adapter.getConfig(key);
let usedKey = key;
if (target === null) {
target = adapter.getFallback();
usedKey = `${adapter.getPrefix()}/common`;
}
if (target !== null) {
resolutionState.config = target;
resolutionState.currentKey = usedKey;
// 更新 CSS 类名
resolutionState.cssClass = adapter.getCssClass(key);
resolutionState.pixelRatio = pr;
resolutionState.windowWidth = w;
resolutionState.windowHeight = h;
console.log(`[ResolutionAdapt] Applied config: ${usedKey}, cssClass: ${resolutionState.cssClass}`);
}
}
// ========================================================================
// 5. 钩子函数 (Hooks)
// ========================================================================
export function useResolutionConfig() : AppResolutionConfig {
// 如果尚未初始化(比如在 App.uvue 之前调用),尝试初始化一次
if (!isRegistryInitialized) {
updateResolutionConfig();
}
return resolutionState.config;
}
/**
* 根据当前设备的 pixelRatio 自动选择最佳图片
* @param img 响应式图片配置对象
* @returns 最佳图片路径
*/
export function getResponsiveImage(img: ResponsiveImage): string {
const pr = resolutionState.pixelRatio;
// 3x 屏优先找 x3 -> x2 -> x1
if (pr >= 3) {
if (img.x3 !== null) return img.x3;
if (img.x2 !== null) return img.x2;
}
// 2x 屏优先找 x2 -> x3 -> x1
if (pr >= 2) {
if (img.x2 !== null) return img.x2;
if (img.x3 !== null) return img.x3;
}
// 默认返回 1倍图
return img.x1;
}
import { ResponsiveImage } from "./types/index.uts";
import { getResponsiveImage } from "./core.uts";
/**
* 获取响应式图片处理函数
* 在 setup 中调用此 hook,返回一个可以直接在 template 中使用的函数
*/
export function useResponsiveImage() {
// 返回一个符合模板调用要求的 wrapper 函数
const getResImg = (img: ResponsiveImage): string => {
return getResponsiveImage(img);
};
return getResImg;
}
// 导出适配器
export { IResolutionAdapter, resolutionAdapters } from "./adapter.uts";
// 导出核心逻辑和工具函数
export { getResponsiveImage, updateResolutionConfig, useResolutionConfig } from "./core.uts";
// 导出 Hooks
export { useResponsiveImage } from './hooks.uts';
// 导出注册表
export { initRegistry, landscapeMap, portraitMap } from "./registry.uts";
// 导出状态
export { resolutionState, ResolutionState } from "./store.uts";
// 导出类型
export * from "./types/index.uts";
import { DemoPageConfig } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "100rpx",
paddingRight: "100rpx",
heroImageWidth: "600px",
heroImageSrc: {
x1: "/static/images/landscape/1024/study-hero.png",
x2: "/static/images/landscape/1024/study-hero@2x.png"
},
titleFontSize: "80rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "150rpx",
paddingRight: "150rpx",
heroImageWidth: "800px",
heroImageSrc: {
x1: "/static/images/landscape/1920/study-hero.png",
x2: "/static/images/landscape/1920/study-hero@2x.png"
},
titleFontSize: "48rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "32rpx",
paddingRight: "32rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/common/study-hero.png",
x2: "/static/images/common/study-hero@2x.png"
},
titleFontSize: "32rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
import { DemoPageConfig } from "../../types/index.uts";
export const demoConfig : DemoPageConfig = {
paddingLeft: "24rpx",
paddingRight: "24rpx",
heroImageWidth: "100%",
heroImageSrc: {
x1: "/static/images/portrait/common/study-hero.png",
x2: "/static/images/portrait/common/study-hero@2x.png"
},
titleFontSize: "30rpx"
};
import { AppResolutionConfig } from "../../types/index.uts";
import { demoConfig } from "./demo.uts";
export const config : AppResolutionConfig = {
demo: demoConfig
};
// ========================================================================
// 1. 静态导入所有支持的分辨率配置 (Static Import)
// 新增分辨率时,请在此处导入并在 initRegistry 中注册
// ========================================================================
import { config as ls_1174 } from "./landscape/1174x768/index.uts";
import { config as ls_1920 } from "./landscape/1920x1080/index.uts";
// Landscape (横屏)
import { config as ls_common } from "./landscape/common/index.uts";
// Portrait (竖屏)
import { config as pt_common } from "./portrait/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 2. 配置注册表 (Registry)
// ========================================================================
export const landscapeMap = new Map<string, AppResolutionConfig>();
export const portraitMap = new Map<string, AppResolutionConfig>();
// eslint-disable-next-line import/no-mutable-exports
let isRegistryInitialized = false;
// 定义配置映射表,方便统一管理和循环注册
const landscapeConfigs = {
"common": ls_common,
"1174x768": ls_1174,
"1920x1080": ls_1920
} as UTSJSONObject;
const portraitConfigs = {
"common": pt_common
// "768x1024": pt_768
} as UTSJSONObject;
export function initRegistry() {
if (isRegistryInitialized) return;
// 批量注册横屏配置
// UTS 遍历 JSONObject
for (const key in landscapeConfigs) {
const conf = landscapeConfigs[key] as AppResolutionConfig;
landscapeMap.set(key, conf);
}
// 批量注册竖屏配置
for (const key in portraitConfigs) {
const conf = portraitConfigs[key] as AppResolutionConfig;
portraitMap.set(key, conf);
}
isRegistryInitialized = true;
}
export { isRegistryInitialized };
import { reactive } from "vue";
import { config as ls_common } from "./landscape/common/index.uts";
import { AppResolutionConfig } from "./types/index.uts";
// ========================================================================
// 3. 全局状态 (Global State)
// ========================================================================
// 使用 reactive 包装,以便在 Vue 模板中自动更新
export type ResolutionState = {
config: AppResolutionConfig
cssClass: string // 新增:用于根元素的 CSS 类名
currentKey: string
pixelRatio: number
windowHeight: number
windowWidth: number
}
// 纯数据对象,不包含逻辑,避免循环依赖
export const resolutionState = reactive({
config: ls_common, // 初始默认值
currentKey: "init",
cssClass: "layout-default",
pixelRatio: 1,
windowWidth: 0,
windowHeight: 0
} as ResolutionState);
export type ResponsiveImage = {
x1: string
x2?: string // 可选
x3?: string // 可选
}
export type DemoPageConfig = {
heroImageSrc: ResponsiveImage
heroImageWidth: string
paddingLeft: string
paddingRight: string
titleFontSize: string
}
// 可以在这里添加其他页面的配置类型
// export type HomePageConfig = { ... }
export type AppResolutionConfig = {
demo: DemoPageConfig
// home: HomePageConfig
}
import { createSSRApp } from "vue"; import { createSSRApp } from "vue";
import App from "./App.uvue"; // 引入分辨率适配模块
import { resolutionState, useResponsiveImage } from "@/config/resolution-adapt/index.uts";
import { logger } from "@/services/logger"; import { logger } from "@/services/logger";
import DBRecord from "@/services/recorder/DBRecord.uts"; import DBRecord from "@/services/recorder/DBRecord.uts";
import App from "./App.uvue";
import { appMixin } from "./utilsApi"; import { appMixin } from "./utilsApi";
export function createApp() { export function createApp() {
const app = createSSRApp(App); const app = createSSRApp(App);
// 挂载日志模块到 uni.$logger // 挂载日志模块到 uni.$logger
// logger.mount(); // logger.mount();
initDB(); initDB();
appMixin(app); appMixin(app);
// 注入全局分辨率适配属性
app.config.globalProperties.$resState = resolutionState;
// 注意:在 main.ts 中,useResponsiveImage 返回的函数可以直接挂载
// 但因为 useResponsiveImage 本身返回的是一个闭包函数,我们直接挂载它返回的函数可能更方便
// 或者我们直接挂载一个 getter 函数
app.config.globalProperties.$getResImg = useResponsiveImage();
return { return {
app app
......
...@@ -68,7 +68,8 @@ ...@@ -68,7 +68,8 @@
"^scene$": "@/pages/common/components/Scene.uvue", "^scene$": "@/pages/common/components/Scene.uvue",
"^no-data$": "@/pages/common/components/NoData.uvue", "^no-data$": "@/pages/common/components/NoData.uvue",
"^home-frame$": "@/components/HomeFrame/index.uvue", "^home-frame$": "@/components/HomeFrame/index.uvue",
"^layout-root$": "@/components/LayoutRoot/index.uvue" "^layout-root$": "@/components/LayoutRoot/index.uvue",
"^Layout$": "@/components/Layout/index.uvue"
} }
}, },
"globalStyle": { "globalStyle": {
......
/* pages/common/login/styles/common.scss */
.layout {
flex: 1;
align-items: center;
justify-content: center;
}
.bg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('@/assets/activeityCenterBg.png');
background-size: 100% 100%;
}
.login {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
.title {
margin-bottom: 16px;
font-size: 48px;
font-weight: 600;
color: #333;
text-align: center;
}
.sub-title {
margin: 24px 0;
font-size: 16px;
font-weight: 500;
color: #1a1a1a;
}
.input {
box-sizing: border-box;
display: flex;
align-items: center;
width: 400px;
height: 56px;
padding-left: 20px;
margin-bottom: 20px;
background: #f7f8fa;
border-radius: 28px;
input {
flex: 1;
height: 100%;
font-size: 16px;
}
.icon {
display: flex;
flex-shrink: 0;
align-items: center;
height: 100%;
padding: 0 20px;
margin-left: auto;
}
.code-btn {
flex-shrink: 0;
margin-right: 20px;
font-size: 16px;
font-weight: 500;
color: #2c66f7;
border: none;
}
.code-disabled {
color: #9b9b9e;
}
}
.btn {
display: flex;
align-items: center;
justify-content: center;
width: 400px;
height: 56px;
font-size: 20px;
font-weight: 600;
color: #fff;
background: #2c66f7;
border-radius: 28px;
}
.btn[disabled]:not([type]),
.btn[disabled][type='default'] {
background: #c9c9c9 !important;
}
.form-footer {
display: flex;
flex-direction: column;
justify-content: center;
padding-left: 72px;
margin-top: 20px;
.autoLogin {
display: flex;
align-items: center;
margin-right: 10px;
margin-bottom: 19px;
.uni-icons {
margin-right: 4px;
}
text {
color: #2c66f7;
}
}
}
}
.app-code {
position: fixed;
bottom: 10px;
left: 50%;
font-size: 12px;
line-height: 20px;
color: #999;
transform: translate(-50%);
.icon-clone {
width: 12px;
height: 12px;
margin-left: 10px;
}
}
/* pages/common/login/styles/landscape.scss */
.layout {
/* 针对 1920x1080 的样式 */
&.layout-landscape-1920x1080 {
.login {
width: 600px;
padding-top: 150px;
.title {
font-size: 48px;
color: #2c66f7; /* 大屏下强调色 */
}
.btn {
height: 100px;
font-size: 36px;
line-height: 100px;
}
}
}
/* 针对 1174x768 的样式 */
&.layout-landscape-1174x768 {
.login {
background-color: blue;
}
.title{
color: #fff;
}
}
/* 兜底样式 (Common Landscape) */
&.layout-landscape-common {
.login {
width: 50%;
min-width: 400px;
}
}
}
/* pages/common/login/styles/portrait.scss */
.layout {
/* 针对竖屏的兜底样式 */
&.layout-portrait-common {
.login {
width: 90%;
margin-top: 200px; /* 竖屏下让登录框靠下一点 */
.title {
font-size: 36px;
}
}
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!