找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/module/adapt/UIEqualAdaptCmponent.ts
1import { _decorator, Component, view, UITransform } from 'cc';
2const { ccclass, property } = _decorator;
3
4/**
5 * 等比适配组件
6 * 功能:保证宽/高铺满屏幕,同时保持原始宽高比
7 */
8@ccclass('UIEqualAdaptCmponent')
9export class UIEqualAdaptCmponent extends Component {
10 @property({ type: UITransform, tooltip: "需要适配的UI元素" })
11 private uiTransform: UITransform | null = null;
12
13 onLoad() {
14 // 如果没有指定uiTransform,则获取当前节点的UITransform组件
15 if (!this.uiTransform) {
16 this.uiTransform = this.node.getComponent(UITransform);
17 }
18
19 if (this.uiTransform) {
20 this.adapt();
21 }
22 }
23
24 onDestroy() {
25
26 }
27
28 /**
29 * 执行等比适配
30 */
31 private adapt() {
32 if (!this.uiTransform) return;
33
34 // 获取屏幕尺寸
35 const visibleSize = view.getVisibleSize();
36 const screenWidth = visibleSize.width;
37 const screenHeight = visibleSize.height;
38
39 // 获取UI元素的原始尺寸
40 const originWidth = this.uiTransform.contentSize.width;
41 const originHeight = this.uiTransform.contentSize.height;
42
43 // 计算原始宽高比
44 const originRatio = originWidth / originHeight;
45
46 // 计算新的尺寸,保持原始宽高比
47 let newWidth = screenWidth;
48 let newHeight = screenWidth / originRatio;
49
50 // 如果按宽度铺满后,高度小于屏幕高度,则以高度为基准
51 if (newHeight < screenHeight) {
52 newHeight = screenHeight;
53 newWidth = screenHeight * originRatio;
54 }
55 // 应用新的尺寸
56 this.uiTransform.setContentSize(newWidth, newHeight);
57
58
59 // 确保UI元素居中显示
60 this.node.setPosition(0, 0);
61 }
62}
讲解62 行
等比铺满人工通读

UIEqualAdaptCmponent.ts

由节点加载驱动,优先使用编辑器绑定的 UITransform,否则查本节点组件。先按可见宽度计算等比高度,高度不足再按屏幕高度反推宽度,最终尺寸保存到目标变换组件;居中移动的却始终是脚本所在节点。

先看 onLoad 的目标选择,再看 adapt 的两次尺寸计算和末尾定位。

特殊处理与易错点

  • 易错点目标可绑定别的节点,但 setPosition 操作的是 this.node。
  • 设计采用覆盖屏幕策略,超出屏幕的另一边允许裁切。
8注释等比适配组件 功能:保证宽/高铺满屏幕,同时保持原始宽高比
9注释UIEqualAdaptCmponent:等比适配组件 功能:保证宽/高铺满屏幕,同时保持原始宽高比
11属性实际被修改尺寸的目标组件,可与脚本节点不同。
13方法取得绑定或本节点变换组件后执行等比铺满适配。
15注释如果没有指定uiTransform,则获取当前节点的UITransform组件
24方法销毁回调为空,不撤销已经写入的尺寸和位置。
31方法按覆盖屏幕的比例重算尺寸并把脚本节点归零。
35注释获取屏幕尺寸
40注释获取UI元素的原始尺寸
44注释计算原始宽高比
47注释计算新的尺寸,保持原始宽高比
51注释如果按宽度铺满后,高度小于屏幕高度,则以高度为基准
56注释应用新的尺寸
60注释确保UI元素居中显示