/** * 该类用于屏幕适配,一般挂载与Canvas节点 */ import { _decorator, Component, Node, UITransform, View, Widget ,screen} from 'cc'; const { ccclass, property } = _decorator; @ccclass('Adapter') export class ScreenAdapter extends Component { public static instance: ScreenAdapter = null as unknown as ScreenAdapter; onLoad() { if (ScreenAdapter.instance === null) { ScreenAdapter.instance = this; } else { ScreenAdapter.instance.destroy(); return; } console.log("屏幕适配组件加载!", screen, screen.devicePixelRatio, screen.resolution, screen.windowSize, screen.windowSize.width, screen.windowSize.height); //获取当前平台(设备)显示的有效分辨率(宽、高) let deviceScreenW = screen.windowSize.width; let deviceScreenH = screen.windowSize.height; //获取当前节点(Canvas)变换组件,用于节点尺寸的获取和屏幕适配的设置 let _transform = this.getComponent(UITransform); //获取当前节点(Canvas)的宽高尺寸 let nodeCurW = _transform.contentSize.width; let nodeCurH = _transform.contentSize.height; //通过平台(设备)与节点的宽高比例获取最小值-即 let srcScaleForShowAll = Math.min(deviceScreenW / nodeCurW, deviceScreenH / nodeCurH); console.log("当前最小缩放", srcScaleForShowAll); let realWidth = nodeCurW * srcScaleForShowAll; let realHeight = nodeCurH * srcScaleForShowAll; console.log(`计算后的尺寸${nodeCurW * (deviceScreenW / realWidth)}, ${nodeCurH * (deviceScreenH / realHeight)}`); // 2. 基于第一步的数据,再做节点宽高适配 _transform.setContentSize(nodeCurW * (deviceScreenW / realWidth),nodeCurH * (deviceScreenH / realHeight)) // // 3. 因为本节点的宽高发生了改变,所以要手动更新剩下子节点的宽高 this._updateAllChildNodeWidget(this.node); console.log(`适配尺寸数据详情:视图[${deviceScreenW}, ${deviceScreenH}],缩放[系数-${srcScaleForShowAll},比例-${realWidth}, ${realHeight}],实际尺寸[${_transform.contentSize.width}, ${_transform.contentSize.height}]`) // if (CC_DEBUG) { // cc.log(`节点在SHOW_ALL模式下展示的宽高: ${realWidth} x ${realHeight}`); // cc.log(`节点在SHOW_ALL模式下展示的缩放: ${srcScaleForShowAll}`); // cc.log( // `节点在SHOW_ALL模式下做全屏处理后的实际宽高(${cc.view.getCanvasSize().width}x${ // cc.view.getCanvasSize().height // })等价于于原节点的宽高(${this.node.width}x${this.node.height})` // ); // } } private _updateAllChildNodeWidget(node: Node) { if (node == null) { return; } let widget = node.getComponent(Widget); if (widget != null) { widget.updateAlignment(); } if (node.children.length == 0) { return; } node.children.forEach((childNode: Node) => { this._updateAllChildNodeWidget(childNode); }); } }