cocos creator 适配那种 底板特大本身不做自适应 然后让上层节点做针对性自适应

const { ccclass, property, menu, requireComponent } = cc._decorator;

@ccclass
@requireComponent(cc.Widget)
@menu('we/adapt/WEAdapBgNotChangetUI(动态均分间距))')
export default class WEAdapBgNotChangetUI extends cc.Component {
    private curWidth: number;
    private curAllWidth: number;
    private tarAllWidth: number;

    /** 排列的组件 */
    @property(cc.Node)
    private adaptTarNode: cc.Node = null;

    protected onLoad(): void {
        this.adaptTarNode.on('size-changed', this.onSizeChanged, this);
        this.curWidth = this.node.width;
        this.curAllWidth = we.core.projectConfig.designResolution.width; // 1280
    }

    protected start(): void {
        this.scheduleOnce(() => {
            this.onSizeChanged();
        }, 0);
    }

    protected onDestroy(): void {
        this.adaptTarNode.off('size-changed', this.onSizeChanged, this);
    }

    private onSizeChanged() {
        this.tarAllWidth = this.adaptTarNode.width;
        let width = Math.abs(this.tarAllWidth - this.curAllWidth) * 0.5 + this.curWidth;
        this.node.width = width;
        let item = this.node.children[0];
        item.x = this.getLayPosX(width);
        let activeCount = this.getActiveCount(item);
        if (activeCount > 0) {
            let center = Math.floor(activeCount * 0.5);
            if (activeCount % 2 == 1) {
                let dis = width / (item.children.length + 1);
                let index = 0;
                for (let i = 0; i < item.children.length; i++) {
                    const v = item.children[i];
                    if (v.active) {
                        let posX = dis * (index - center);
                        v.x = posX;
                        index++;
                    }
                }
            } else {
                let dis = width / (item.children.length + 1);
                let index = 0;
                for (let i = 0; i < item.children.length; i++) {
                    const v = item.children[i];
                    if (v.active) {
                        let posX = dis * (index + 0.5 - center);
                        v.x = posX;
                        index++;
                    }
                }
            }
        }
    }

    private getActiveCount(item: cc.Node) {
        let count = 0;
        for (let i = 0; i < item.children.length; i++) {
            const v = item.children[i];
            if (v.active) {
                count++;
            }
        }
        return count;
    }

    /**
     * 计算节点的水平中心点位置
     * @param node 目标节点
     * @returns 水平中心点位置
     */
    private getLayPosX(width: number) {
        let posX = width * (0.5 - this.node.anchorX);
        return posX;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值