import { _decorator, Component, view, Node } from 'cc'; const { ccclass, property } = _decorator; @ccclass('BackgroundAdapter') export class BackgroundAdapter extends Component { @property(Node) background: Node = null; onLoad() { // 检查背景节点是否已绑定 if (!this.background) { console.error('背景节点未绑定,请在编辑器中将背景节点拖拽到 background 属性中。'); return; } // 获取设计分辨率和实际屏幕分辨率 const designResolution = view.getDesignResolutionSize(); const frameSize = view.getFrameSize(); // 计算设计分辨率和屏幕分辨率的比例 const designRatio = designResolution.width / designResolution.height; const frameRatio = frameSize.width / frameSize.height; // 根据比例调整背景缩放 if (frameRatio > designRatio) { // 屏幕更宽,调整背景宽度 const scale = frameRatio / designRatio; this.background.setScale(scale, 1, 1); } else { // 屏幕更窄,调整背景高度 const scale = designRatio / frameRatio; this.background.setScale(1, scale, 1); } } }