根据文档多分辨率屏幕适配
比葫芦画瓢写了个ScreenAdaptation适配的代码
设计分辨率 750x1334【竖屏】
canvas 挂载 ScreenAdaptation,但是没有生效,大神帮忙看看错在哪里了
import { _decorator, Component, Size, view, Canvas, ResolutionPolicy } from ‘cc’;
const { ccclass, property } = _decorator;
@ccclass(‘ScreenAdaptation’)
export default class ScreenAdaptation extends Component {
//横板设计分辨率
@property(Size)
private designSiveH: Size = new Size(1334, 750);
private clientSize: Size = new Size(0, 0);
//竖版设计分辨率
@property(Size)
private designSiveV: Size = new Size(750, 1334);
//H 横板 V 竖版 记录当前
private _screenOrientation: string = “”;
@property(Canvas)
public canvas: Canvas = null!;
public start() {
this.changeDesignResolution();
}
public update(){
//检测分辨率 某些环境下对尺寸改变添加回调函数会有严重延时所以放在update检测
this.changeDesignResolution();
}
//对分辨率进行检测
public changeDesignResolution(){
let size = screen;
//未检测到尺寸变化则跳出函数
if (size.width == this.clientSize.width && size.height == this.clientSize.height) {
return;
}
this.clientSize = new Size(size.width, size.height);
console.log("=======clientSize")
console.log(this.clientSize)
//计算当前屏幕比
let proportion: number = (size.width / size.height);
//屏占比切换条件 当宽>高 设定为横屏,当然你可以根据实际调整
if (proportion >= 1) {
//屏幕和横板设计相比比较宽
if (proportion >= this.designSiveH.width / this.designSiveH.height) {
//重新设定canvas设计分辨率
//var designResolution = view.getDesignResolutionSize()
let w = size.width * (this.designSiveH.height / size.height)
let h = this.designSiveH.height
view.setDesignResolutionSize(w, h, ResolutionPolicy.SHOW_ALL)
} else {
let w = this.designSiveH.width
let h = size.height * (this.designSiveH.width / size.width)
view.setDesignResolutionSize(w, h, ResolutionPolicy.SHOW_ALL)
//重新设定canvas设计分辨率
}
if (this._screenOrientation != "H" ) {
this._screenOrientation = "H";
//通知所有需要改变场景变成横屏
}
}else{
//竖屏处理
console.log("=======policy1")
console.log(proportion)
console.log(this.designSiveV.width / this.designSiveV.height)
if (proportion >= this.designSiveV.width / this.designSiveV.height) {
//屏幕比较宽
console.log("=======policy2")
let w = size.width * (this.designSiveV.height / size.height)
let h = this.designSiveV.height
view.setDesignResolutionSize(w, h, ResolutionPolicy.SHOW_ALL)
console.log(this.node)
} else {
console.log("=======policy3")
let w = this.designSiveV.width
let h = size.height * (this.designSiveV.width / size.width)
view.setDesignResolutionSize(w, h, ResolutionPolicy.SHOW_ALL)
console.log(this.node)
}
if (this._screenOrientation != "V" ) {
this._screenOrientation = "V";
}
}
}
}