core-egret.StageScaleMode

egret.StageScaleMode 使用範例


class Main extends eui.UILayer {

    protected createChildren(): void {
        super.createChildren();
        egret.lifecycle.onPause = () => egret.ticker.pause();
        egret.lifecycle.onResume = () => egret.ticker.resume();
        egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
        egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
        this.runGame();
    }

    private async loadResource() {
        let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
        await RES.loadConfig('resource/default.res.json', 'resource/');
        await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
        await RES.loadGroup('preload', 0, loadingView);
        this.stage.removeChild(loadingView);
    }

    private async runGame() {
        await this.loadResource();
        // --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---

        // 官方解說
        // https://docs.egret.com/engine/docs/api/engine/egret.StageScaleMode
        // https://docs.egret.com/engine/docs/screenAdaptation/zoomMode
        // 設置方式
        // this.stage.scaleMode = egret.StageScaleMode.SHOW_ALL;


        // 自定義模式 (類似 SHOW_ALL 模式, 但是 canvas 是滿版的)
        // 限制場景寬高
        const contentWidth = 800;
        const contentHeight = 600;

        // 黑色背景
        const bg = new eui.Rect;
        bg.width = contentWidth;
        bg.height = contentHeight;
        bg.horizontalCenter = 0;
        bg.verticalCenter = 0;
        this.addChild(bg);

        const stage = egret.MainContext.instance.stage;
        // 設置 stage 大小
        stage.setContentSize(contentWidth, contentHeight);
        const onStageResize = (()=>{
            stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
            if (contentHeight > stage.stageHeight) {
                // stage.scaleMode 設置會呼叫 eui.UIEvent.RESIZE 避免循環呼叫所以移除監聽
                stage.removeEventListener(eui.UIEvent.RESIZE, onStageResize, this); 
                stage.scaleMode = egret.StageScaleMode.FIXED_HEIGHT;
                // 設置好 stage.scaleMode 後再監聽事件
                stage.addEventListener(eui.UIEvent.RESIZE, onStageResize, this);
            }
        }).bind(this); // 用 bind 會產生新函式並且函式內部 this 為 Main 而不是 Window
        onStageResize();
        stage.addEventListener(eui.UIEvent.RESIZE, onStageResize, this);

    }

}

spacer

沒有留言:

張貼留言