mutoo
3/19/2014 - 1:58 AM

sprite_tint.js

var SpriteTint = cc.Sprite.extend({
    initWithSprite: function (sprite) {
        // bind sprite
        this._sprite = sprite;
        this.addChild(this._sprite);

        // create tint texture
        this._texture = cc.RenderTexture.create(
            this._sprite.getBoundingBox().width,
            this._sprite.getBoundingBox().height
        );
        // start with white color
        this._texture.beginWithClear(255, 255, 255, 255);
        // get rig of alpha pixels
        this._sprite.setBlendFunc(gl.ZERO, gl.SRC_ALPHA);
        this._sprite.setPosition(
            this._sprite.getBoundingBox().width/2,
            this._sprite.getBoundingBox().height/2
        );
        this._sprite.visit();
        this._texture.end();
        this._texture.retain();
        
        // reset sprite
        this._sprite.setBlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
        this._sprite.setPosition(cc.POINT_ZERO);

        // create and hide tint skin
        this._tint = cc.Sprite.createWithTexture(this._texture.getSprite().getTexture());
        this._tint.setScaleY(-1);
        this._tint.setOpacity(0);
        this.addChild(this._tint);

        this.setCascadeOpacityEnabled(true);
        return true;
    },
    setTint: function (r, g, b, a) {
        // you can change tint skin's color
        this._tint.setColor(cc.c3b(r, g, b));
        // and opacity
        this._tint.setOpacity(a);
    },
    onExit: function () {
        this._texture.release();
        this._super();
    }
});

SpriteTint.createWithSprite = function (sprite) {
    var sg = new SpriteTint();
    if (sg && sg.initWithSprite(sprite)) {
        return sg;
    }
    return null;
};

// example
// =======

var sprite = cc.Sprite.create("your_sprite.png");
var spriteWithTint = SpriteTint.createWithSprite(sprite);
addChild(spriteWithTint);

// tint to white with 50% transparency
spriteWithTint.setTint(255,255,255,128);