Files
18xchat/assets/Scripts/chat18x/ui/uiTool/SpriteResize.ts
T

90 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-08-25 20:15:42 +08:00
import {
_decorator,
Component,
Sprite,
UITransform,
view,
Size,
isValid,
} from "cc";
2025-09-21 20:36:19 +08:00
import { logger } from "db://assets/Scripts/Main/Common/Logger";
2025-08-25 20:15:42 +08:00
const { ccclass } = _decorator;
/**
* 精灵自动调整组件
* 功能:使精灵保持原始宽高比并覆盖整个屏幕
* 触发时机:GameObject 激活时、屏幕尺寸变化时
*/
@ccclass("SpriteResize")
export class SpriteResize extends Component {
private sprite: Sprite = null;
private uiTransform: UITransform = null;
private lastScreenSize: Size = new Size();
onLoad() {
// 获取必要组件
this.sprite = this.getComponent(Sprite);
this.uiTransform = this.getComponent(UITransform);
if (!this.sprite) {
2025-09-21 20:36:19 +08:00
logger.warn("SpriteResize: 未找到 Sprite 组件");
2025-08-25 20:15:42 +08:00
return;
}
if (!this.uiTransform) {
2025-09-21 20:36:19 +08:00
logger.warn("SpriteResize: 未找到 UITransform 组件");
2025-08-25 20:15:42 +08:00
return;
}
}
onEnable() {
// 激活时立即调整尺寸
this.adjustSize();
}
/**
* 调整精灵尺寸以覆盖整个屏幕
* 保持原始宽高比,使用 cover 策略
*/
private adjustSize() {
if (!isValid(this.sprite) || !isValid(this.uiTransform)) {
return;
}
const spriteFrame = this.sprite.spriteFrame;
if (!spriteFrame) {
return;
}
// 获取屏幕尺寸
const screenSize = view.getVisibleSize();
// 获取精灵原始尺寸
const originalSize = spriteFrame.originalSize;
if (!originalSize || originalSize.width <= 0 || originalSize.height <= 0) {
return;
}
// 计算缩放比例(使用较大值以确保覆盖全屏)
const scaleX = screenSize.width / originalSize.width;
const scaleY = screenSize.height / originalSize.height;
const scale = Math.max(scaleX, scaleY);
// 计算新的尺寸
const newWidth = originalSize.width * scale;
const newHeight = originalSize.height * scale;
// 应用新尺寸
this.uiTransform.setContentSize(newWidth, newHeight);
}
/**
* 手动触发尺寸调整
* 可在外部调用,例如当 SpriteFrame 改变时
*/
public forceResize() {
this.adjustSize();
}
}