cocos2d-x中使图片背景全透明(另一种方法)

  1. CCLayerColor::initWithColor(ccc4(255,255,255,255));

  2.         CCImage *pImage = new CCImage();
  3.         pImage->autorelease();
  4.         pImage->initWithImageFile("arraw.png",CCImage::EImageFormat::kFmtPng);

  5.         //遍历图片的所有像素.
  6.         unsigned char *pData = pImage->getData();
  7.         int nPixelIndex = 0;
  8.         for (int nCol = 0; nCol < pImage->getHeight(); nCol ++)
  9.         {
  10.             for (int nRow = 0; nRow < pImage->getWidth(); nRow ++)
  11.             {
  12.                 //取图片的RGB值.
  13.                 int nBeginPos = nPixelIndex;
  14.                 unsigned int nRValue = pData[nPixelIndex];
  15.                 nPixelIndex++;
  16.                 unsigned int nGValue = pData[nPixelIndex];
  17.                 nPixelIndex ++;
  18.                 unsigned int nBValue = pData[nPixelIndex];
  19.                 nPixelIndex ++;
  20.                 unsigned int nAValue = pData[nPixelIndex];
  21.                 nPixelIndex ++;
  22.             
  23.                 int nAlphaRatio = 0;
  24.                 //本代码的核心:取RGB中的最大值赋给nAlphaRatio。如果nAlphaRatio为0,则像素中的alpha通道就为0,否则像素中的 
  25.                 //alpha通道值就是nAlphaRatio。这样做是为了在图片中颜色渐变过渡比较大的区域实现平滑的过渡。让最终形成的
  26.                 //图片看起来不粗糙.
  27.                 nAlphaRatio = nRValue>nGValue?(nRValue>nBValue?nRValue:nBValue):(nGValue>nBValue?nGValue:nBValue);
  28.                 if(nAlphaRatio != 0)
  29.                 {
  30.                     nAValue = nAlphaRatio;
  31.                 }
  32.                 else
  33.                 {
  34.                     nAValue= 0;
  35.                 }

  36.                 pData[nBeginPos] = (unsigned char)nRValue;
  37.                 pData[nBeginPos+ 1] = (unsigned char)nGValue;
  38.                 pData[nBeginPos + 2] = (unsigned char)nBValue;
  39.                 //修改原图的alpha值.
  40.                 pData[nBeginPos + 3] = (unsigned char)nAValue;
  41.             }
  42.         }

  43.         CCTexture2D *pTexture = new CCTexture2D;
  44.         pTexture->autorelease();
  45.         pTexture->initWithImage(pImage);
  46.         CCTexture2DPixelFormat ccpf = pTexture->getPixelFormat();
  47.         CCAssert(ccpf == kTexture2DPixelFormat_RGBA8888, "your png file's pixel format is not RGBA8888 or not have alpha panel");

  48.         CCSprite* pArrowSprite= new CCSprite();
  49.         pArrowSprite->initWithTexture(pTexture);
  50.         CCSize size = CCDirector::sharedDirector()->getWinSize();
  51.         pArrowSprite->setPosition(ccp(size.width/+ 20, size.height/- 20));
  52.         this->addChild(pArrowSprite, 6);
直接看代码注释就懂了。贴上效果图,打完收工。

你可能感兴趣的:(cocos2d,图形,cocos2d-x)