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;
}
}