const {ccclass, property} = cc._decorator;
@ccclass
export default class CanvasLayout extends cc.Component {
curDR:cc.Size = null;
onLoad () {
var cvs = cc.Canvas.instance;
//保存原始设计分辨率,供屏幕大小变化时使用
if(!this.curDR){
this.curDR = cvs.designResolution;
}
var dr = this.curDR;
var s = cc.view.getFrameSize();
var rw = s.width;
var rh = s.height;
var finalW = rw;
var finalH = rh;
if((rw/rh) > (dr.width / dr.height)){
//如果更长,则用定高
finalH = dr.height;
finalW = finalH * rw/rh;
}
else{
//如果更短,则用定宽
finalW = dr.width;
finalH = rh/rw * finalW;
}
cvs.designResolution = cc.size(finalW, finalH);
cvs.node.width = finalW;
cvs.node.height = finalH;
}
}
挂在Canvas上面
下面是cocos creator 3.0 版本的适配代码,也是挂在Canvas上
import { Canvas, Component, ResolutionPolicy, Size, UITransform, view, _decorator } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('CanvasLayout')
export class CanvasLayout extends Component {
curDR: Size = null;
onLoad() {
var cvs = this.getComponent(Canvas);
var trans = this.getComponent(UITransform);
//保存原始设计分辨率,供屏幕大小变化时使用
if (!this.curDR) {
this.curDR = view.getDesignResolutionSize();
}
var dr = this.curDR;
var s = view.getFrameSize();
var rw = s.width;
var rh = s.height;
var finalW = rw;
var finalH = rh;
var sc = 1;
if ((rw / rh) > (dr.width / dr.height)) {
//如果更长,则用定高
finalH = dr.height;
sc = rw / rh;
finalW = finalH * sc;
}
else {
//如果更短,则用定宽
finalW = dr.width;
sc = rh / rw ;
finalH = sc * finalW;
}
view.setDesignResolutionSize(finalW,finalH,ResolutionPolicy.SHOW_ALL);
trans.setContentSize(finalW,finalH);
trans.node.setScale(sc,sc);
}
}