通过新建一个空白的画布 RenderTexture ,然后将精灵绘制在这块画布上,获取到单独的Image,getData到Image里面的数据后,对每个像素增加一定的值,实现高亮效果
注意:
1.已经绘制的精灵无法通过这个来进行修改,例如已经addchild显示在屏幕中的精灵
auto star_sprite = static_cast<Sprite* >(rootNode->getChildByName("star_1"));
Sprite* new_star = Sprite::createWithTexture(star_sprite->getTexture());
auto blue = Sprite::create("star.png");
//blue->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
auto highlight_star = getHighlightSprite(new_star);
//highlight_star->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
Point p = star_sprite->getPosition();
rootNode->removeChildByName("star_1");
rootNode->addChild(highlight_star);
highlight_star->setName("star_1");
highlight_star->setPosition(p);
需要获取后替换掉
2.Director::getInstance()->getRenderer()->render();这句很重要,因为在cocos2dx 3.0中,绘制是下一帧才进行绘制的,如果没有这个可能会导致黑屏或者下一帧才出现
cocos2d::Sprite* HelloWorld::getHighlightSprite(Sprite* normalsprite) {
if (!normalsprite) {
return NULL;
}
//normalsprite = Sprite::create("star.png");
Point p = normalsprite->getAnchorPoint();
normalsprite->setAnchorPoint(Vec2(0, 0));
RenderTexture *outTexture = RenderTexture::create(normalsprite->getContentSize().width, normalsprite->getContentSize().height, Texture2D::PixelFormat::RGBA8888);
outTexture->retain();
outTexture->beginWithClear(0, 0, 0, 0);
normalsprite->visit();
outTexture->end();
Director::getInstance()->getRenderer()->render();
normalsprite->setAnchorPoint(p);
Image* image = outTexture->newImage();
//Image *image = new Image();
//image->initWithImageFile("blue.jpg");
unsigned char* pdata = image->getData();
if (!image->getData()) {
CCLOG("hehe");
}
CCLOG("%s",pdata);
int index = 0;
for (int i = 0; i < image->getHeight(); i++) {
for (int j = 0; j < image->getWidth(); j++) {
int iHightlightPlus = 50;
int nPos = index;
unsigned int iB = pdata[index++];
unsigned int iG = pdata[index++];
unsigned int iR = pdata[index++];
unsigned int iO = pdata[index++];
//CCLOG("iO=%d", iO);
iB = (iB + iHightlightPlus) > 255 ? 255 : (iB + iHightlightPlus);
iG = (iG + iHightlightPlus) > 255 ? 255 : (iG + iHightlightPlus);
iR = (iR + iHightlightPlus) > 255 ? 255 : (iR + iHightlightPlus);
pdata[nPos] = iB;
pdata[nPos + 1] = iG;
pdata[nPos + 2] = iR;
}
}
Texture2D* texture2D = new Texture2D;
texture2D->initWithImage(image);
Sprite* outputSprite = Sprite::createWithTexture(texture2D);
delete image;
texture2D->release();
CCLOG("okay!!!!");
return outputSprite;
}