Created
August 20, 2018 07:11
-
-
Save johnsoncodehk/c989ed0252944c3a43abc4c6e80ea24c to your computer and use it in GitHub Desktop.
AspectRatioFitter for CocosCreator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let AspectMode = cc.Enum({ | |
None: 0, | |
WidthControlsHeight: 1, | |
HeightControlsWidth: 2, | |
FitInParent: 3, | |
EnvelopeParent: 4, | |
}); | |
cc.Class({ | |
extends: cc.Component, | |
editor: CC_EDITOR && { | |
executeInEditMode: true, | |
disallowMultiple: true, | |
}, | |
properties: { | |
aspectMode: { | |
default: AspectMode.None, | |
type: AspectMode, | |
}, | |
aspectRatio: 1, | |
}, | |
statics: { | |
AspectMode: AspectMode, | |
}, | |
update: function (dt) { | |
this.updateRect(); | |
}, | |
updateRect() { | |
switch (this.aspectMode) { | |
case AspectMode.None: | |
{ | |
break; | |
} | |
case AspectMode.HeightControlsWidth: | |
{ | |
this.node.width = this.node.height * this.aspectRatio; | |
break; | |
} | |
case AspectMode.WidthControlsHeight: | |
{ | |
this.node.height = this.node.width / this.aspectRatio; | |
break; | |
} | |
case AspectMode.FitInParent: | |
case AspectMode.EnvelopeParent: | |
{ | |
let sizeDelta = cc.Vec2.ZERO; | |
let parentSize = this.getParentSize(); | |
if ((parentSize.y * this.aspectRatio < parentSize.x) ^ (this.aspectMode == AspectMode.FitInParent)) { | |
sizeDelta.y = parentSize.x / this.aspectRatio; | |
sizeDelta.x = sizeDelta.y * this.aspectRatio; | |
} | |
else { | |
sizeDelta.x = parentSize.y * this.aspectRatio; | |
sizeDelta.y = sizeDelta.x / this.aspectRatio; | |
} | |
this.setSize(sizeDelta); | |
break; | |
} | |
} | |
}, | |
getParentSize() { | |
let parent = this.node.parent; | |
if (!parent) | |
return cc.Vec2.ZERO; | |
return new cc.Vec2(parent.width, parent.height); | |
}, | |
setSize(size) { | |
this.node.width = size.x; | |
this.node.height = size.y; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment