如何在cocos2d js / c ++中获取Sprite像素alpha信息

时间:2017-06-13 11:45:31

标签: cocos2d-x-3.0 cocos2d-js

我正在进行刮刮和赢比赛,我使用了clipper节点。 但我想知道整个精灵是剪辑的事件吗?

有没有其他方法可以了解它,请帮助我

1 个答案:

答案 0 :(得分:1)

I solved this issue by using following method:-

I create one rendure texture and add an sprite on it. 

I found answer here:- http://discuss.cocos2d-x.org/t/render-texture-get-percentage-of-transparent/21123  
here is the code:-

  var WINDOW_WIDTH = cc.director.getWinSize().width;

  var WINDOW_HEIGHT = cc.director.getWinSize().height;

  rt = new cc.RenderTexture(WINDOW_WIDTH, WINDOW_HEIGHT, 
  sprite.getTexture().getPixelFormat());
  rt.setPosition(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2);
  this.addChild(rt, 5);

getPercentageTransparent: function () {
        //
        var s = rt.getSprite().getContentSize();
        var tx = s.width;
        var ty = s.height;

        var bitsPerPixel = 4 * 8;
        var bytesPerPixel = bitsPerPixel / 8;
        var bytesPerRow = bytesPerPixel * tx;
        var myDataLength = bytesPerRow * ty;

        var numberOfPixels = tx * ty;
        var numberOfTransparent = 0;

        var rawImagePixels = new Uint8Array(myDataLength);
        rt.begin();
        gl.readPixels(0, 0, tx, ty, gl.RGBA, gl.UNSIGNED_BYTE, rawImagePixels);
        rt.end();

        var x, y;

        for (y = 0; y < ty; y++) {
            // just want the last byte (alpha) for each pixel
            for (x = 0; x < tx; x++) {
                var alpha = rawImagePixels[(y * 4 * tx + ((x * 4) + 3))];

                if (alpha < 1) {
                    numberOfTransparent++;
                }
            }
        }
        cc.log("Number of pixels" + numberOfPixels);
        cc.log("Number of Trasparent" + numberOfTransparent);
        cc.log("percentage " + (numberOfTransparent / numberOfPixels) * 100);
        return (numberOfTransparent / numberOfPixels) * 100;
    },