【自定义组件】CocosCreator 限制图片大小组件(用于图片尺寸不一样时,固定图片大小,防止超出范围)

图片放在物品栏中,图片可能大小不一,导致超出物品栏底图的范围,所以需要限制图片的大小。

原理是图片超过限制大小,会进行缩放。

let node;         //图片node
let fixedSize;    //限制大小
var max = Math.max(node.width, node.height);
node.scale = fixedSize / max; 

例如图片80x120,fixedSize为100。

那么图片node.scale = 100/120 = 0.83,缩放后图片的大小变成66.4x99.6,在限制的100以内。 

ImgFixedSize.ts组件代码:

const { ccclass, property } = cc._decorator;
 
/**
 * 图片限制尺寸
 * @author chenkai 2021.6.24
 */
@ccclass
export default class ImgFixedSize extends cc.Component {
 
    public get fixedSize(){
        return this._fixedSize;
    }

    @property({type:cc.Integer, tooltip:"固定尺寸"})
    public set fixedSize(value){
        this._fixedSize = value;
        this.onSizeChanged();
    }    

    /**固定尺寸 */
    private _fixedSize:number = 0;

    onLoad() {
        this.node.on(cc.Node.EventType.SIZE_CHANGED, this.onSizeChanged, this);
        this.onSizeChanged();
    }
 
    /**当尺寸变化时,重置node节点大小 */
    onSizeChanged() {
        var width = this.node.width;
        var height = this.node.height;
        var max = Math.max(width, height);
        this.node.scale = this.fixedSize / max;
    }
}

  

在图标所在节点上绑定ImgFixedSize.ts组件,并设置固定大小为50。cc.Sprite属性SizeMode需要设置为TRIMMED并勾选Trim,表示图片大小为裁剪透明像素后的大小。

现在用3张图片来测试,一张大人物图593x800,一个小刀图标38x38,一个小刀图标64x64。

 

 3张图会等比例缩放到<=50像素,不会超出边框。

原文地址:https://www.cnblogs.com/gamedaybyday/p/14929199.html