cocos2d判断精灵某点颜色是否有效

用了一段时间的Cocos2d-3.x,遇到一个问题,就是判断触摸的精灵像素是否有效,而cocos并没有获取Sprite某一点像素值的方法。

在网上看到有人通过保存Image像素的方法,来记录像素值。或者通过Image::initWithImageFile 来实现获取像素值。

前者浪费内存,后者浪费性能。今天来分享一下我的实现方法

/** 
 * 判断Sprite某点像素值是否有效
 * @author devefx
 * @date 2016/8/13
 */
bool isNonInvalidPixel(Sprite* sprite, const Point& point)
{
    Rect rect = sprite->getBoundingBox();

    if (rect.containsPoint(point))
    {
        GLint oldFBO;
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldFBO);

        GLuint frameBuffer;
        glGenFramebuffers(1, &frameBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, sprite->getTexture()->getName(), 0);

        CCASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");

        Rect frameRect = sprite->getSpriteFrame()->getRectInPixels();
        // subtract anchor point
        GLint x = point.x - rect.getMinX();
        GLint y = point.y - rect.getMinY();
        // convert left-handed
        y = frameRect.size.height - 1 - y;
        // add frame origin
        x = x + frameRect.origin.x;
        y = y + frameRect.origin.y;

        Color4B color;

        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &color);

        glBindFramebuffer(GL_FRAMEBUFFER, oldFBO);
        glDeleteFramebuffers(1, &frameBuffer);

        return color.a != 0;
    }
    return false;
}

主要是使用FBO关联已经加载的texture,再通过glReadPixels来获取像素值

猜你喜欢

转载自blog.csdn.net/devefx/article/details/52198661