[置顶] Cocos2d-x 让精灵图像变灰的方法

本文参考了下面两篇博文

http://www.cocos2dev.com/?p=325
http://blog.csdn.net/u012940116/article/details/17003841


综合了上面两篇博文中对OpenGLES着色器的配置代码,经过试验后,得到以下代码


//函数声明
static void addGray(CCSprite* sp);  
static void removeGray(CCSprite* sp);

//函数本体


void 你的类名::addGray(CCSprite* sp)
{
  do  
    {  
        GLchar* pszFragSource =
		"#ifdef GL_ES \n \
		 precision mediump float; \n \
		 #endif \n \
		 uniform sampler2D u_texture; \n \
		 varying vec2 v_texCoord; \n \
		 varying vec4 v_fragmentColor; \n \
		 void main(void) \n \
		 { \n \
		 // Convert to greyscale using NTSC weightings \n \
		 vec4 col = texture2D(u_texture, v_texCoord); \n \
		 float grey = dot(col.rgb, vec3(0.299, 0.587, 0.114)); \n \
		 gl_FragColor = vec4(grey, grey, grey, col.a); \n \
		 }";
		CCGLProgram* pProgram = new CCGLProgram();
		pProgram->initWithVertexShaderByteArray(ccPositionTextureColor_vert, pszFragSource);
        sp->setShaderProgram(pProgram);  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);  
        sp->getShaderProgram()->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);  
        sp->getShaderProgram()->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->link();  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->updateUniforms();  
        CHECK_GL_ERROR_DEBUG();  
    } while (0);  
}


void 你的类名::removeGray(CCSprite* sp)
{
  do  
    {  
        CCGLProgram* pProgram = CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor);  
        sp->setShaderProgram(pProgram);  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);  
        sp->getShaderProgram()->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);  
        sp->getShaderProgram()->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->link();  
        CHECK_GL_ERROR_DEBUG();  
          
        sp->getShaderProgram()->updateUniforms();  
        CHECK_GL_ERROR_DEBUG();  
    } while (0);
}

Cocos2d-x中让CCSprite变灰(Gray)的简单办法 这篇博文中的Shader Program常量kCCShader_PositionTextureGray在现在的cocos2d-x版本中没有设置,不知道这篇博文的博主用的是什么版本

你可能感兴趣的:(android,color,特效,cocos2d-x,opengles)