import { _decorator, Component, Enum, UITransform, view } from 'cc'; const { ccclass, property } = _decorator; @ccclass('AdaptToScreen') export class AdaptToScreen extends Component { // 增加左右适配选项:Top、Down、Left、Right @property({ type: Enum({ Top: 0, Down: 1, Left: 2, Right: 3 }) }) public position: number = 0; @property public offset: number = 0; @property public scale: number = 1; start() { this.adaptToScreen(); } adaptToScreen() { const screenHeight = view.getVisibleSize().height; const screenWidth = view.getVisibleSize().width; console.log(screenHeight, screenWidth); const uiTransform = this.node.getComponent(UITransform); // 适配顶部 if (this.position === 0) { this.node.setPosition(this.node.position.x / this.scale, (screenHeight / 2 - uiTransform.height / 2 - this.offset) / this.scale); if (mtec.cc.is_long_screen) { this.node.setPosition(this.node.position.x / this.scale, (this.node.position.y - 100 - this.offset) / this.scale); } } // 适配底部 else if (this.position === 1) { this.node.setPosition(this.node.position.x / this.scale, (-(screenHeight / 2 - uiTransform.height / 2) + this.offset) / this.scale); } // 适配左侧 else if (this.position === 2) { this.node.setPosition((-(screenWidth / 2 - uiTransform.width / 2) + this.offset) / this.scale, this.node.position.y / this.scale); } // 适配右侧 else if (this.position === 3) { this.node.setPosition((screenWidth / 2 - uiTransform.width / 2 - this.offset) / this.scale, this.node.position.y / this.scale); } } }