消消方块阵换皮表情
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.9 KiB

1 week ago
import { _decorator, Component, Node, Sprite, UITransform } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('AdapSize')
export class AdapSize extends Component {
container: UITransform;
sprite: Sprite;
protected onLoad(): void {
this.container = this.node.getComponent(UITransform);
this.sprite = this.getComponent(Sprite);
}
// 可以手动调用此方法进行适配
public resize() {
if (!this.container || !this.sprite || !this.sprite.spriteFrame) {
console.warn("缺少组件或 SpriteFrame");
return;
}
const textureSize = this.sprite.spriteFrame.originalSize;
const containerSize = this.container.contentSize;
if (textureSize.width === 0 || textureSize.height === 0) {
console.warn("图片尺寸为0,请确认 SpriteFrame 是否加载完成");
return;
}
// 计算缩放比例
const scaleX = containerSize.width / textureSize.width;
const scaleY = containerSize.height / textureSize.height;
const scale = Math.min(scaleX, scaleY); // contain 模式
// 设置缩放和位置
const finalWidth = textureSize.width * scale;
const finalHeight = textureSize.height * scale;
const uiTransform = this.sprite.node.getComponent(UITransform);
if (uiTransform) {
uiTransform.setContentSize(finalWidth, finalHeight);
uiTransform.anchorX = 0.5;
uiTransform.anchorY = 0.5;
this.sprite.node.setPosition(0, 0); // 居中
}
}
// 生命周期钩子中自动调用
onEnable() {
this.resize();
}
// 如果容器尺寸会动态变化,可以监听窗口事件
start() {
// 例如监听窗口尺寸变化
// cc.game.on(cc.EVENT_RESIZE, this.resize, this);
}
onDestroy() {
// cc.game.off(cc.EVENT_RESIZE, this.resize, this);
}
}