转自:http://cocos2d.cocoachina.com/bbs/forum.php?mod=viewthread&tid=822&extra=&page=1
ocos2d-x好像没有实现原生的加亮和变灰的效果,所以自己研究了一番,实现起来也不难,要同时用到CCImage、CCTexture、CCSprite。
主要的思路是通过CCImage先载入图片,然后getData()获取图片数据,接着逐一获取各像素的RGB值(代码基于jpg,若是png则需要获取RGBA值),通过相应方法修改各像素点的值。之后将该CCImange加载到CCTexture2D中,再由CCSprite载入,然后即可自由操作CCSprite。
以上相当于是在生成CCSprite时载入已加亮或变灰了的图片,至于如何将已有的CCSprite加亮或变灰,尚等研究。
希望对大家有帮助:)
代码如下:
// !这里是以jpg图片为例,若载入的是png,则要注意处理alpha通道
CCImage *finalImage = new CCImage;
finalImage->initWithImageFile("11.jpg", CCImage::kFmtJpg);
unsigned char *pData = finalImage->getData();
int iIndex = 0;
for (int i = 0; i < finalImage->getHeight(); i ++)
{
for (int j = 0; j < finalImage->getWidth(); j ++)
{
// highlight
int iHightlightPlus = 100;
int iBPos = iIndex;
unsigned int iB = pData[iIndex];
iIndex ++;
unsigned int iG = pData[iIndex];
iIndex ++;
unsigned int iR = 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;
}
}
// 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 iGray = 0.3 * iR + 0.6 * iG + 0.1 * iB;
// pData[iBPos] = pData[iBPos + 1] = pData[iBPos + 2] = (unsigned char)iGray;
// }
// }
CCTexture2D *texture = new CCTexture2D;
texture->initWithImage(finalImage);
pSprite = CCSprite::spriteWithTexture(texture);
pSprite->setPosition(ccp(size.width/2 + 20, size.height/2 - 20));
this->addChild(pSprite, 6);
delete finalImage;
texture->release();