转一篇,不过本位介绍的加亮和之前我想做的加亮闪缩效果还是有差别。
主要的思路是通过CCImage先载入图片,然后getData()获取图片数据,接着逐一获取各像素的RGB值(代码基于jpg,若是png则需要获取RGBA值),通过相应方法修改各像素点的值。之后将该CCImange加载到CCTexture2D中,再由CCSprite载入,然后即可自由操作CCSprite。
以上相当于是在生成CCSprite时载入已加亮或变灰了的图片,至于如何将已有的CCSprite加亮或变灰,尚等研究。
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | //根据现有CCSprite,变亮和变灰 static CCSprite* graylightWithCCSprite(CCSprite* oldSprite,bool isLight) { //CCSprite转成CCimage CCPoint p = oldSprite->getAnchorPoint(); oldSprite->setAnchorPoint(ccp(0,0)); CCRenderTexture *outTexture = CCRenderTexture::create((int)oldSprite->getContentSize().width,(int)oldSprite->getContentSize().height); outTexture->begin(); oldSprite->visit(); outTexture->end(); oldSprite->setAnchorPoint(p); CCImage* finalImage = outTexture->newCCImage(); unsigned char *pData = finalImage->getData(); int iIndex = 0; if(isLight) { for (int i = 0; i < finalImage->getHeight(); i ++) { for (int j = 0; j < finalImage->getWidth(); j ++) { // highlight int iHightlightPlus = 50; int iBPos = iIndex; unsigned int iB = pData[iIndex]; iIndex ++; unsigned int iG = pData[iIndex]; iIndex ++; unsigned int iR = pData[iIndex]; iIndex ++; //unsigned int o = pData[iIndex]; iIndex ++; //原来的示例缺少 iB = (iB + iHightlightPlus > 255 ? 255 : iB + iHightlightPlus); iG = (iG + iHightlightPlus > 255 ? 255 : iG + iHightlightPlus); iR = (iR + iHightlightPlus > 255 ? 255 : iR + iHightlightPlus); // iR = (iR < 0 ? 0 : iR); // iG = (iG < 0 ? 0 : iG); // iB = (iB < 0 ? 0 : iB); pData[iBPos] = (unsigned char)iB; pData[iBPos + 1] = (unsigned char)iG; pData[iBPos + 2] = (unsigned char)iR; } } }else{ for (int i = 0; i < finalImage->getHeight(); i ++) { for (int j = 0; j < finalImage->getWidth(); j ++) { // gray int iBPos = iIndex; unsigned int iB = pData[iIndex]; iIndex ++; unsigned int iG = pData[iIndex]; iIndex ++; unsigned int iR = pData[iIndex]; iIndex ++; //unsigned int o = pData[iIndex]; iIndex ++; //原来的示例缺少 unsigned int iGray = 0.3 * iR + 0.4 * iG + 0.2 * iB; pData[iBPos] = pData[iBPos + 1] = pData[iBPos + 2] = (unsigned char)iGray; } } } CCTexture2D *texture = new CCTexture2D; texture->initWithImage(finalImage); CCSprite* newSprite = CCSprite::createWithTexture(texture); delete finalImage; texture->release(); return newSprite; } |
参考
有两处注释的地方是对原来例子修改的地方,不知道什么原因,原来的例子少了一个alpha通道