[Cocos creator学习篇] 屏幕自适配脚本

今天给大家带来目前我在用的一个屏幕自适配的脚本。用法也比较简单。
新建一个脚本把下面的脚本复制进去就可以了,在你要做适配的节点,挂上widget组件,把脚本拖进去就可以了。

/**
 * IPXWidget适配器
 * 适用于非16:9屏幕贴边UI
 * @author yxx0
 */

const { ccclass, property } = cc._decorator;

@ccclass
export default class IPXWidgetComponent extends cc.Component {

    @property(cc.Boolean)
    public isPortait: boolean = true;

    @property({ type: cc.Float, tooltip: "需要勾选对应widget组件对齐的方向方可生效" })
    public left: number = 0;

    @property({ type: cc.Float, tooltip: "需要勾选对应widget组件对齐的方向方可生效" })
    public right: number = 0;

    @property({ type: cc.Float, tooltip: "需要勾选对应widget组件对齐的方向方可生效" })
    public top: number = 0;

    @property({ type: cc.Float, tooltip: "需要勾选对应widget组件对齐的方向方可生效" })
    public bottom: number = 0;

    private widget: cc.Widget = null;

    protected onLoad(): void {
        this.widget = this.node.getComponent(cc.Widget);

        this.checkWidgetStatus();
    }

    /**
     * 检查widget状态
     */
    protected checkWidgetStatus(): void {
        if (!this.widget) return console.error('节点:', this.node.name, 'WidgetComponent 未绑定widget组件');

        const pos = cc.winSize;

        if (this.isPortait) {
            // 屏幕比不为16:9 (竖屏)
            if (!(Math.ceil(pos.height * 9 / 16) > pos.width - 2 && Math.ceil(pos.height * 9 / 16) < pos.width + 2)) {
                this.setWidgetValue();
            }
        } else {
            // 屏幕比不为16:9 (横屏)
            if (!(Math.ceil(pos.width * 9 / 16) > pos.height - 2 && Math.ceil(pos.width * 9 / 16) < pos.height + 2)) {
                this.setWidgetValue();
            }
        }
    }

    /**
     * 设置widget数值
     */
    private setWidgetValue(): void {
        if (this.widget.isAlignBottom) this.widget.bottom = this.bottom;
        if (this.widget.isAlignTop) this.widget.top = this.top;
        if (this.widget.isAlignLeft) this.widget.left = this.left;
        if (this.widget.isAlignRight) this.widget.right = this.right;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值