Cocos2d-x开发--使用CCRenderTexture将矩形图片裁剪成圆形显示

日前,自己在做项目的过程中遇到此需求:需要将Facebook好友的方形头像变成圆形头像展示。通过网上的搜罗研究,发现使用CCRenderTexture是个不错的方法,归纳总结之后,形成了下面这个方法

其实,用这个方法不仅可以将图片裁成圆形,而是可以裁成任何你想要的形状。关键只在于你使用的是何种形状的蒙版图片而已。

方法如下:

CCSprite * UnivCoreTest::maskedSprite(CCSprite *textureSprite)
{
    CCSprite * maskSprite = CCSprite::create("circle_mask.png");
    CCRenderTexture * renderTexture = CCRenderTexture::create(maskSprite->getContentSize().width,maskSprite->getContentSize().height);
    
    maskSprite->setPosition(ccp(maskSprite->getContentSize().width / 2,maskSprite->getContentSize().height / 2));
    textureSprite->setPosition(ccp(textureSprite->getContentSize().width / 2,textureSprite->getContentSize().height / 2));

    maskSprite->setBlendFunc((ccBlendFunc){GL_ONE,GL_ZERO});
    textureSprite->setBlendFunc((ccBlendFunc){GL_DST_ALPHA,GL_ZERO});
    
    renderTexture->begin();
    maskSprite->visit();
    textureSprite->visit();
    renderTexture->end();

    CCSprite * retval = CCSprite::createWithTexture(renderTexture->getSprite()->getTexture());
    retval->setFlipY(true);
    return retval;
}

函数形参“textureSprite”是待裁剪的方形图片,当然读者需要先将其创建成CCSprite再传入。

方法中出现的“circle_mask.png”图片是整个裁剪过程的关键,它决定了你的原始图片会被裁剪成什么形状。

这里作者需要将原始图片裁成圆形,故而使用了如下样式的蒙版图片


图片是一个白色的圆形,四周是透明的。


方法最后返回的CCSprite即是经过裁剪的以圆形方式显示图片

相关文章

操作步骤 1、创建cocos2d-x工程 2、新建 Scene1.cpp Scene1.h Scene1.h代码 #ifndef __SCENE1_H__#defi...
开发环境:OS(WINDOWS 8.1 X64 企业版) cocos2d-x 2.2.1 vs2010 想给vs安装上cocos的模版,执行Install...
把创建项目做成一个批处理,当创建项目时可以省时省力很多。 操作步骤 1、在 E:cocos2d-x-2.2.1toolspr...
https://www.cnblogs.com/JiaoQing/p/3906780.html 四个响应函数 1 EventListenerPhysicsContact* evC...
转载于 http://www.cnblogs.com/kenkofox/p/3926797.html 熟悉js的dom事件或者flash事件的,基本都能立...
ScrollView(滚动容器)加载大量item时会导致游戏界面的卡顿,严重时整个界面会出现卡死的情况。最近项...