LayaBox自定义组件

最近在写自己游戏的过程中,自己写了个ScaleButton(点击带缩放的按钮),通过组件名字,通过附加的方式,来实现游戏中按钮的点击缩放。
但是这样也引来了几个问题,注册麻烦,需要在每个UI界面的类中进行注册,关闭界面的时候还要取消掉特性,非常麻烦。
然后搜索了一番,发现LayaBox的UI工具支持组件扩展,而且也有官方文章告诉你怎么做。
但是!因为我用ts写的代码,发现那文章并不是那么好使,所以自己也做了整理。

准备:
1.引入EditorUI库(放在lib文件夹下)下载
2.在src下新建laya/customUI/路径,并且新建ScaleButton.ts
内容为:

// 正式使用的时候切换为这个
// var Button = laya.ui.Button;

var Button = laya.editorUI.Button;
var scaleTime = 100;
// Laya是为了跟编辑器对齐,拖出的ScaleButton组件生成的代码Laya.ScaleButton对齐
module Laya{
    export class ScaleButton extends Button{
        constructor(skin, label){
            super(skin, label);
            if (skin === void 0) { skin = null; }
            if (label === void 0) { label = ""; }
            /* 设置按钮为单态按钮
            ** 取值:
            ** 1:单态。图片不做切割,按钮的皮肤状态只有一种。
            ** 2:两态。图片将以竖直方向被等比切割为2部分,从上向下,依次为弹起状态皮肤、按下和经过及选中状态皮肤。
            ** 3:三态。图片将以竖直方向被等比切割为2部分,从上向下,依次为弹起状态皮肤、经过状态皮肤、按下和选中状态皮肤
            */
            this.stateNum = 1;
            //添加鼠标按下事件侦听。按时时缩小按钮。
            this.on(Laya.Event.MOUSE_DOWN, this, this.scaleSmall);
            //添加鼠标抬起事件侦听。抬起时还原按钮。
            this.on(Laya.Event.MOUSE_UP, this, this.scaleBig);
            //添加鼠标离开事件侦听。离开时还原按钮。
            this.on(Laya.Event.MOUSE_OUT, this, this.scaleBig);
        }
        public scaleSmall():void{
            //缩小至0.8的缓动效果
            Laya.Tween.to(this, { scaleX: 0.8, scaleY: 0.8 }, scaleTime);
        }
        public scaleBig():void{
            //变大还原的缓动效果
            Laya.Tween.to(this, { scaleX: 1, scaleY: 1 }, scaleTime);
        }
    }
}

然后点击运行,编译出js文件(ScaleButton.js):
复制到:\LayaAirIDE_1.7.5_beta\resources\app\out\vs\layaEditor\renders\custom
在相同目录下创建xml文件(ScaleButton.xml):
内容为:



    
        
    

设置对应的组件展示:
默认展示组件的iconxml中icon属性-在\LayaAirIDE_1.7.5_beta\resources\app\out\vs\layaEditor\laya\icons\components\ScaleButton.png
默认展示的组件外观xml中resName在\LayaAirIDE_1.7.5_beta\resources\app\out\vs\layaEditor\laya\basics\Custom\ScaleButton.png
使用方法:
1.把上述的ts文件中的Button引用改为laya.ui.Button
2.使用前注册组件View.regComponent("ScaleButton", Laya.ScaleButton) //第1个参数是我们开始定组件名字,第2个参数是我们对应的类;

// 需要加载完资源创建UI
Laya.loader.load("res/atlas/comp.json", Laya.Handler.create(this, this.onLoaded), null, Laya.Loader.ATLAS);
public onLoaded(){
    //create btn or craete ui
}

从此你就可以在组件也页签中的Custom文件夹拖出组件来使用我们的ScaleButton。

=========================================================
号外:这个原来是有更好的文档的,更新一下~
移步

你可能感兴趣的:(LayaBox自定义组件)