NodeFitScreen.js 2.67 KB
Newer Older
asdf's avatar
asdf committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

const FitType = {
    Scale: 0,//等比缩放,一般用于背景图
    FullScreen: 1,//铺满全屏,拉伸
    FitMode: 2,//更改canvas适配策略,只能挂在canvas上
    FullHeight: 3,
    FullWidth: 4,
};
const designSize = cc.size(1280, 720);
cc.Class({
    extends: cc.Component,

    properties: {
        FitType: {
            type: cc.Enum(FitType),
            default: 0
        },
    },

    onLoad: function () {
        cc.view.on('canvas-resize', this.refreshFit, this)
        this.refreshFit();
    },
    onDestroy(){
        cc.view.off('canvas-resize', this.refreshFit, this)
    },

    refreshFit() {
        if (this.FitType == FitType.Scale) {
            let winSize = cc.view.getVisibleSize();
            console.log(winSize)
            console.log(this.node.width,this.node.height)
            if(this.node.width >= winSize.width && this.node.height >= winSize.height ){
                return;
            }
            let scale1 = winSize.width / this.node.width;
            let scale2 = winSize.height / this.node.height;
            if (scale1 > scale2) {
                this.node.scale = scale1;
            } else {
                this.node.scale = scale2;
            }
        } else if (this.FitType == FitType.FullScreen) {
            let visiblesize = cc.view.getVisibleSize();
            this.node.width = visiblesize.width;
            this.node.height = visiblesize.height;
        } else if (this.FitType == FitType.FullHeight) {
            let visiblesize = cc.view.getVisibleSize();
            let scale = visiblesize.width / this.node.width;
            this.node.width = scale * this.node.width;
            this.node.height = scale * this.node.height;
        } else if (this.FitType == FitType.FullWidth) {
            let visiblesize = cc.view.getVisibleSize();
            let scale = visiblesize.height / this.node.height;
            this.node.width = scale * this.node.width;
            this.node.height = scale * this.node.height;
        } else {
            let wsize = cc.view.getFrameSize();
            let scaleW = wsize.width / designSize.width;
            let scaleH = wsize.height / designSize.height;

            let pCanvas = this.node.getComponent(cc.Canvas);
            if (pCanvas) {
                if (scaleW > scaleH) { //更宽了要fitHeight, 否则height就留黑边了;
                    pCanvas.fitHeight = true;
                    pCanvas.fitWidth = false;
                } else { //更高;
                    pCanvas.fitHeight = false;
                    pCanvas.fitWidth = true;
                }
            } else {
                console.error("fitmode模式只能用在canvas节点上");
            }
        }
    },
});