530
技術社區[雲棲]
cocos2d-x中使圖片背景全透明(另一種方法)
-
CCLayerColor::initWithColor(ccc4(255,255,255,255));
-
-
CCImage *pImage = new CCImage();
-
pImage->autorelease();
-
pImage->initWithImageFile("arraw.png",CCImage::EImageFormat::kFmtPng);
-
-
//遍曆圖片的所有像素.
-
unsigned char *pData = pImage->getData();
-
int nPixelIndex = 0;
-
for (int nCol = 0; nCol < pImage->getHeight(); nCol ++)
-
{
-
for (int nRow = 0; nRow < pImage->getWidth(); nRow ++)
-
{
-
//取圖片的RGB值.
-
int nBeginPos = nPixelIndex;
-
unsigned int nRValue = pData[nPixelIndex];
-
nPixelIndex++;
-
unsigned int nGValue = pData[nPixelIndex];
-
nPixelIndex ++;
-
unsigned int nBValue = pData[nPixelIndex];
-
nPixelIndex ++;
-
unsigned int nAValue = pData[nPixelIndex];
-
nPixelIndex ++;
-
-
int nAlphaRatio = 0;
-
//本代碼的核心:取RGB中的最大值賦給nAlphaRatio。如果nAlphaRatio為0,則像素中的alpha通道就為0,否則像素中的
-
//alpha通道值就是nAlphaRatio。這樣做是為了在圖片中顏色漸變過渡比較大的區域實現平滑的過渡。讓最終形成的
-
//圖片看起來不粗糙.
-
nAlphaRatio = nRValue>nGValue?(nRValue>nBValue?nRValue:nBValue):(nGValue>nBValue?nGValue:nBValue);
-
if(nAlphaRatio != 0)
-
{
-
nAValue = nAlphaRatio;
-
}
-
else
-
{
-
nAValue= 0;
-
}
-
-
pData[nBeginPos] = (unsigned
char)nRValue;
-
pData[nBeginPos+ 1] = (unsigned
char)nGValue;
-
pData[nBeginPos + 2] = (unsigned
char)nBValue;
-
//修改原圖的alpha值.
-
pData[nBeginPos + 3] = (unsigned
char)nAValue;
-
}
-
}
-
-
CCTexture2D *pTexture = new CCTexture2D;
-
pTexture->autorelease();
-
pTexture->initWithImage(pImage);
-
CCTexture2DPixelFormat ccpf = pTexture->getPixelFormat();
-
CCAssert(ccpf == kTexture2DPixelFormat_RGBA8888, "your
png file's pixel format is not RGBA8888 or not have alpha panel");
-
-
CCSprite* pArrowSprite= new CCSprite();
-
pArrowSprite->initWithTexture(pTexture);
-
CCSize size = CCDirector::sharedDirector()->getWinSize();
-
pArrowSprite->setPosition(ccp(size.width/2 + 20, size.height/2 - 20));
- this->addChild(pArrowSprite, 6);
直接看代碼注釋就懂了。貼上效果圖,打完收工。

最後更新:2017-04-03 12:56:43