COCOS2D-X字体描边

cocos2d-x3.16版本,原有的描边函数enableOutline会在渐出时出错,文字消失了描边停留在那里。

所以自己在网上找了个描边的函数,另外修改了一部分,做成了一个COCOS2D的工具类。


LabelWithStroke.h


#ifndef __LabelWithStroke_H__
#define __LabelWithStroke_H__


#include "cocos2d.h"
#include "define/define.h"
#include "util/Utils.h"
USING_NS_CC;


class LabelWithStroke :public Node
{
Label *up = nullptr, *down = nullptr, *left = nullptr, *right = nullptr,*center = nullptr;
public:
CREATE_FUNC(LabelWithStroke);
void setLabel(const std::string& text, const std::string& fontFilePath, float fontSize, const Color4B & color4);
void setStroke(const Color4B &color3, float lineWidth = 1.0f);
Action * runAction(Action* action, Action* actionCenter);
void removeCenter();
void removeStroke();
virtual const Size& getContentSize() const ;
};


#endif // __LabelWithStroke


LabelWithStroke.cpp

#include "LabelWithStroke.h"


void LabelWithStroke::setLabel(const std::string& text
, const std::string& fontFilePath, float fontSize, const Color4B & color4)
{
TTFConfig ttf(fontFilePath, fontSize, GlyphCollection::DYNAMIC);
center = Label::createWithTTF(ttf, text);
center->setTextColor(color4);
this->addChild(center);

up = Label::createWithTTF(ttf, text);
down = Label::createWithTTF(ttf, text);
left = Label::createWithTTF(ttf, text);
right = Label::createWithTTF(ttf, text);
}


void LabelWithStroke::setStroke(const Color4B & color4, float lineWidth)
{

auto string = center->getString();
auto fontName = center->getTTFConfig().fontFilePath;
auto fontSize = center->getTTFConfig().fontSize;
Point centerPoint = center->getPosition();
//描边CCLabelTTF 上
up->setTextColor(color4);
//up->setAnchorPoint(Point(0.5f,0.5f));
up->setPosition(Point(centerPoint.x, centerPoint.y + lineWidth));
this->addChild(up, -1);


//描边CCLabelTTF 下
down->setTextColor(color4);
//down->setAnchorPoint(Point(0.5f, 0.5f));
down->setPosition(Point(centerPoint.x, centerPoint.y - lineWidth));
this->addChild(down, -1);


//描边CCLabelTTF 左
left->setPosition(Point(centerPoint.x - lineWidth, centerPoint.y));
//left->setAnchorPoint(Point(0.5f, 0.5f));
left->setTextColor(color4);
this->addChild(left, -1);


//描边CCLabelTTF 右
right->setTextColor(color4);
//right->setAnchorPoint(Point(0.5f, 0.5f));
right->setPosition(Point(centerPoint.x + lineWidth, centerPoint.y));
this->addChild(right, -1);


}


Action * LabelWithStroke::runAction(Action* action, Action* actionCenter)
{
if(up)
up->runAction(action->clone());
if (down)
down->runAction(action->clone());
if (left)
left->runAction(action->clone());
if (right)
right->runAction(action->clone());
if (center)
center->runAction(actionCenter);
//这些动画结束了要把center去掉
return action;
}


void LabelWithStroke::removeCenter()
{
removeChild(center);
}


void LabelWithStroke::removeStroke()
{
removeChild(up);
removeChild(down);
removeChild(left);
removeChild(right);
}


const Size & LabelWithStroke::getContentSize() const
{
// TODO: 在此处插入 return 语句
return center->getContentSize();
}

你可能感兴趣的:(cocos,c++)