cocos下实现圆形头像最初始考虑的是ClippingNode,但是无论实心圆形蒙层使用DrawNode还是图片都会遮罩出很严重的锯齿
于是取个巧,使用实体圆蒙层后,在上层再盖一个无锯齿的圆环,做出来最终的效果,自我感觉还可以
把工具类取出来保存:
头文件UserIconSprite.h:
#ifndef __Ci__UserIconSprite__
#define __Ci__UserIconSprite__
#include
#include
USING_NS_CC;
class UserIconSprite:public Sprite
{
public:
CREATE_FUNC(UserIconSprite);
bool init();
void changeIcon(std::string path);
void setSpriteFrameName(std::string path); //通过图片路径设置头像
void setSprite(Sprite* img); //添加Sprite为头像
private:
Sprite* getImgFromPath(std::string path,std::string defautImg = "[email protected]"); //传入图片的绝对路径
Sprite* userImg;
Sprite* mark;
ClippingNode* clip;
};
#endif /* defined(__Ci__UserIconSprite__) */
具体实现UserIconSprite.cpp:
#include "UserIconSprite.h"
#include "SceneManager.h"
bool UserIconSprite::init()
{
if(!Sprite::init()){
returnfalse;
}
clip =ClippingNode::create();
clip->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
clip->setInverted(false);
clip->setAlphaThreshold(0.0f);
mark =Sprite::create("[email protected]"); //一个圆形图片当蒙层,也可以使用DrawNode
mark->setPosition(0,0);
clip->setStencil(mark);
this->addChild(clip);
this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
auto circle =Sprite::create("[email protected]");//一个大小类似的圆环图片
this->addChild(circle,zOrder_LAYER);
circle->setPosition(0,0);
returntrue;
}
void UserIconSprite::changeIcon(string path)
{
clip->removeAllChildrenWithCleanup(true);
setSpriteFrameName(path);
}
void UserIconSprite::setSpriteFrameName(string path)
{
userImg =getImgFromPath(path);
setSprite(userImg);
}
void UserIconSprite::setSprite(Sprite* img)
{
userImg = img;
userImg->setPosition(0,0);
clip->addChild(userImg,zOrder_LAYER);
}
Sprite* UserIconSprite::getImgFromPath(std::string path,std::string defautImg)
{
Sprite* mImg;
if(FileUtils::getInstance()->isFileExist(path)) //若图片不存在则使用默认头像
{
auto mUerImg =new Image();
mUerImg->initWithImageFile(path);
auto texture =new Texture2D();
texture->initWithImage(mUerImg);
mUerImg->release();
mImg = Sprite::createWithTexture(texture);
}else{
mImg = Sprite::create(defautImg);
}
return mImg;
}
用法:
UserIconSprite* userSprite =UserIconSprite::create();
userSprite->setSprite(Sprite::createWithSpriteFrameName("[email protected]"));
this->addChild(userSprite ,0);