在想cocos适配之前,我们想想网页是怎么适配的。浏览器有各种规格,网页的一般做法是:背景图片铺满,网页内容保持在背景图片上居中,就实现了适应或者适配。css一般这样:
.bg{height:582px;background-image:url('images/top_team_bg.png');background-size:auto 100%;background-position: center center;background-repeat: no-repeat;}.content {width:1000px;margin:0 auto;}
核心:
background-position: center center;
因为是背景图片,所以横向显示可以不全,但永远会显示中间的部分,就是我们的网页内容。content部分宽度是固定的,并且是居中的。
回到cocos上,原理完全一样,让背景铺满,内容居中。背景铺满,在背景是顶级节点的情况下(和canvas平级),可以用Widget,left:0;right:0;content居中我们用js去控制,下面的代码,在编辑器里我们设置content的宽度是2048,ts代码:adaptScreen(items: Array) {if(cc.director.getVisibleSize().width <= 2048) return;if(items instanceof Array) {items.forEach(item => {try {item.x += Math.floor((cc.director.getVisibleSize().width - 2048) / 2 )} catch(e) {cc.log(e)}})} else {cc.log(items)cc.log('传入的参数必须是数组')}}