【自定義組件】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像素,不會超出邊框。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM