86 lines
2.9 KiB
TypeScript
86 lines
2.9 KiB
TypeScript
import { _decorator, Node, Component, screen, view, ResolutionPolicy, Sprite, sys } from 'cc';
|
|
import { LocalizedLabel } from './i18n/LocalizedLabel';
|
|
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('LayoutAdapter')
|
|
export class LayoutAdapter extends Component {
|
|
|
|
@property(Node)
|
|
BG_01: Node = null;
|
|
|
|
|
|
@property(Node)
|
|
rotateNode: Node = null;
|
|
|
|
sprite: Sprite = null;
|
|
protected onLoad(): void {
|
|
this.sprite = this.BG_01.getComponent(Sprite);
|
|
this.rotateNode.active = false;
|
|
this.rotateNode.getChildByName('tips').active = false;
|
|
}
|
|
|
|
|
|
start(): void {
|
|
screen.on('window-resize', this.onWindowResize, this);
|
|
screen.on('orientation-change', this.onWindowResize, this);
|
|
this.onWindowResize();
|
|
this.rotateNode.getChildByName('tips').getComponent(LocalizedLabel).fetchRender();
|
|
this.rotateNode.getChildByName('tips').active = true;
|
|
|
|
}
|
|
|
|
onWindowResize() {
|
|
const designSize = view.getDesignResolutionSize();
|
|
const screenSize0 = view.getVisibleSize(); // 先记录一份(如果你需要对比)
|
|
|
|
// 1) 依据宽高比切换策略
|
|
const screenRatio = screenSize0.width / screenSize0.height;
|
|
const designRatio = designSize.width / designSize.height;
|
|
view.setResolutionPolicy(
|
|
screenRatio > designRatio
|
|
? ResolutionPolicy.FIXED_HEIGHT // 横屏更宽:以高适配
|
|
: ResolutionPolicy.FIXED_WIDTH // 竖屏更窄:以宽适配
|
|
);
|
|
|
|
// 2) 下一帧再取"最终可视尺寸"来计算缩放
|
|
this.scheduleOnce(() => {
|
|
const size = view.getVisibleSize(); // 已更新后的正确值
|
|
const texW = this.sprite.spriteFrame.width;
|
|
const texH = this.sprite.spriteFrame.height;
|
|
const scale = Math.max(size.width / texW, size.height / texH);
|
|
this.BG_01.setScale(scale, scale); // 铺满并保持比例
|
|
|
|
|
|
|
|
if (this.isMobile()) {
|
|
if (size.width > size.height) {
|
|
this.rotateNode.getChildByName('block').setScale(scale, scale);
|
|
this.rotateNode.active = true;
|
|
} else {
|
|
this.rotateNode.getChildByName('block').setScale(scale, scale);
|
|
this.rotateNode.active = false;
|
|
}
|
|
} else {
|
|
this.rotateNode.active = false;
|
|
}
|
|
|
|
}, 0);
|
|
}
|
|
|
|
|
|
onDestroy() {
|
|
screen.off('window-resize', this.onWindowResize, this);
|
|
screen.off('orientation-change', this.onWindowResize, this);
|
|
}
|
|
|
|
isMobile(): boolean {
|
|
return (
|
|
sys.platform === sys.Platform.ANDROID ||
|
|
sys.platform === sys.Platform.IOS ||
|
|
sys.platform === sys.Platform.MOBILE_BROWSER ||
|
|
sys.platform === sys.Platform.UNKNOWN
|
|
);
|
|
}
|
|
|
|
} |