1. 程式人生 > >Cocos2d-x中讓CCSprite變灰(Gray)的簡單辦法

Cocos2d-x中讓CCSprite變灰(Gray)的簡單辦法

之前一直做flash開發,像變灰,高亮,描邊了這些效果非常容易實現,有現成的api直接呼叫即可,cocos2d-x並沒有提供,所以遇到這種需求就得硬著都頭尋求解決方案了,廢話不多說,直接上程式碼:

CCColorUtil.cpp:

//
//  CCColorUtil.cpp
//  quickcocos2dx
//
//  Created by Terran Tian on 13-11-19.
//  Copyright (c) 2013年 qeeplay.com. All rights reserved.
//
#include "CCColorUtil.h"
#include "cocos2d.h"
using namespace cocos2d;
void CCColorUtil::addGray(CCSprite* sp)
{
    do
    {
        CCGLProgram* pProgram = CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureGray);
		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 CCColorUtil::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);
}

CCColorUtil.h:

//
//  CCColorUtil.h
//  quickcocos2dx
//
//  Created by Terran Tian on 13-11-19.
//  Copyright (c) 2013年 qeeplay.com. All rights reserved.
//
#ifndef __quickcocos2dx__CCColorUtil__
#define __quickcocos2dx__CCColorUtil__
#include <iostream>
#endif /* defined(__quickcocos2dx__CCColorUtil__) */
#include "cocos2d.h"
using namespace cocos2d;
class CCColorUtil
{
public:
    static void addGray(CCSprite* sp);
    static void removeGray(CCSprite* sp);
    
};