首先我这里说明一下,因为我们的ui大部分是用CocosStudio做的,所以这里针对的对象基本是都是Widget的子类对象。这里实现有两种方式
第一方式就是直接利用引擎提供的现有的内容来实现。以下两个方法可以实现将Widget置灰,以及从置灰还原原色
//将节点置灰
void addNodeGray(cocos2d::ui::Widget* node){
do{
CC_BREAK_IF(node==nullptr);
const char* key=GLProgram::SHADER_NAME_POSITION_GRAYSCALE;
GLProgram* gLProgram=GLProgramCache::getInstance()->getGLProgram(key);
auto scale9Sprite=dynamic_cast<Scale9Sprite*>(node->getVirtualRenderer());
if(scale9Sprite!=nullptr){
auto sprite=scale9Sprite->getSprite();
if(sprite!=nullptr){
sprite->setGLProgram(gLProgram);
}else{
scale9Sprite->setGLProgram(gLProgram);
}
}
}while (0);
}
//将节点从灰色恢复正常颜色
void removeNodeGray(cocos2d::ui::Widget* node){
do{
CC_BREAK_IF(node==nullptr);
const char* key=GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP;
auto glprogramstate = GLProgramState::getOrCreateWithGLProgramName(key);
auto scale9Sprite=dynamic_cast<Scale9Sprite*>(node->getVirtualRenderer());
if(scale9Sprite!=nullptr){
auto sprite=scale9Sprite->getSprite();
if(sprite!=nullptr){
sprite->setGLProgramState(glprogramstate);
}else{
scale9Sprite->setGLProgramState(glprogramstate);
}
}
}while (0);
}
第二种方式:则是自己提供两个文件gray.fsh和gray.vsh,这两个文件放在项目的Resources目录下
gray.fsh的内容
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
void main()
{
vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114));
gl_FragColor = vec4(gray, gray, gray, v_orColor.a);
}
gray.vsh的内容
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
void main()
{
gl_Position = CC_PMatrix * a_position;
v_fragmentColor = a_color;
v_texCoord = a_texCoord;
}
--------------------------------------------------------------------------------这里是分割线---------------------------------------------------------------------------------------------
//将节点置灰
void addNodeGray(cocos2d::ui::Widget* node){
do{
CC_BREAK_IF(node==nullptr);
GLProgram* gLProgram=GLProgramCache::getInstance()->getGLProgram("black_white");
if(gLProgram==nullptr){
gLProgram = GLProgram::createWithFilenames("gray.vsh", "gray.fsh");
GLProgramCache::getInstance()->addGLProgram(gLProgram,"black_white");
}
auto scale9Sprite=dynamic_cast<Scale9Sprite*>(node->getVirtualRenderer());
if(scale9Sprite!=nullptr){
auto sprite=scale9Sprite->getSprite();
if(sprite!=nullptr){
sprite->setGLProgram(gLProgram);
}else{
scale9Sprite->setGLProgram(gLProgram);
}
}
}while (0);
}
//将节点从灰恢复正常颜色
void removeNodeGray(cocos2d::ui::Widget* node){
do{
CC_BREAK_IF(node==nullptr);
auto glprogramstate = GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
auto scale9Sprite=dynamic_cast<Scale9Sprite*>(node->getVirtualRenderer());
if(scale9Sprite!=nullptr){
auto sprite=scale9Sprite->getSprite();
if(sprite!=nullptr){
sprite->setGLProgramState(glprogramstate);
}else{
scale9Sprite->setGLProgramState(glprogramstate);
}
}
}while (0);
}