How to get Sprite pixel alpha information in cocos2d js/c++

人走茶凉 提交于 2020-01-07 03:15:09

问题


I am working on a scratch and win game, I used clipper node for this. But I want to know the event when whole sprite is clippe?

Is there any other way to know it, plz help me


回答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;
    },


来源:https://stackoverflow.com/questions/44520608/how-to-get-sprite-pixel-alpha-information-in-cocos2d-js-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!