cocos2dx显示CCLabelTTF的指定宽度
2015-10-20 19:42
429 查看
好久不写文章了,现在我用的还是cocos2dx2.2.2版本进行开发,所以一些小功能还是写出来了
如果一个CCLabelTTF的长度太长了,但是全部显示出来,可能效果不好看,所以这里就根据固定长度显示,超过的自动抹去。
方法如下:
void setNameLength(std::string nameStr)
{
int charNum =
0;
int lMax =
0;
CCLabelTTF * nameTTF =
CCLabelTTF::create(nameStr.c_str(),
"Arial", 20);
float strLength = nameTTF->getContentSize().width;
if (strLength > 100) {
charNum =
NAME_DOWN_MAX;
lMax = (180<strLength)?180:strLength;
}
else
{
lMax = strLength;
}
printf("lMax is %d\n", lMax);
std::string string1 = nameStr;
std::string string2;
if (strLength>lMax)
{
const char * s = nameStr.c_str();
int i = 0, j =
0;
while (s[i])
{
if ((s[i] &
0xc0) != 0x80)
{
j++;
if (j>1) {
std::string string3 = string1.substr(0,i).c_str();
nameTTF = CCLabelTTF::create(string3.c_str(),
"Arial", 22);
strLength = nameTTF->getContentSize().width;
if ((strLength)>lMax) {
break;
}
else
{
string2 = string1.substr(0,i).c_str();
}
}
}
i++;
}
}
else
{
string2 = nameStr;
}
CCLabelTTF* pLabelTTF = CCLabelTTF::create(string2.c_str(), "Arial", 32);
pLabelTTF->setPosition(ccp(240, 160));
this->addChild(pLabelTTF);//这个pLabelTTF就是显示固定宽度的区域
}
当然这个功能也可以用遮罩实现,也比较简单
如果一个CCLabelTTF的长度太长了,但是全部显示出来,可能效果不好看,所以这里就根据固定长度显示,超过的自动抹去。
方法如下:
void setNameLength(std::string nameStr)
{
int charNum =
0;
int lMax =
0;
CCLabelTTF * nameTTF =
CCLabelTTF::create(nameStr.c_str(),
"Arial", 20);
float strLength = nameTTF->getContentSize().width;
if (strLength > 100) {
charNum =
NAME_DOWN_MAX;
lMax = (180<strLength)?180:strLength;
}
else
{
lMax = strLength;
}
printf("lMax is %d\n", lMax);
std::string string1 = nameStr;
std::string string2;
if (strLength>lMax)
{
const char * s = nameStr.c_str();
int i = 0, j =
0;
while (s[i])
{
if ((s[i] &
0xc0) != 0x80)
{
j++;
if (j>1) {
std::string string3 = string1.substr(0,i).c_str();
nameTTF = CCLabelTTF::create(string3.c_str(),
"Arial", 22);
strLength = nameTTF->getContentSize().width;
if ((strLength)>lMax) {
break;
}
else
{
string2 = string1.substr(0,i).c_str();
}
}
}
i++;
}
}
else
{
string2 = nameStr;
}
CCLabelTTF* pLabelTTF = CCLabelTTF::create(string2.c_str(), "Arial", 32);
pLabelTTF->setPosition(ccp(240, 160));
this->addChild(pLabelTTF);//这个pLabelTTF就是显示固定宽度的区域
}
当然这个功能也可以用遮罩实现,也比较简单
相关文章推荐
- cocos2d-x 锚点,位置==》动手实验记录 多动手... :)
- Cocos2d-lua-3.8.1在Cocos code ide中创建新项目的问题
- cocos2dx在VS下Label中文显示乱码…
- 关于cocos2dx3.X版本的触摸响应的…
- 关于TileMap(瓦片地图)
- 关于COCOS2d里CCArray使用时的一点…
- Cocos2d-JS项目之四:UI界面的优化
- Cocos2d-JS项目之三:使用合图
- Cocos2d提供的字体!共57种(有对照的字体图)
- Cocos2d-x 3.x——AnchorPoint 和Position 关系
- Cocos2d-x3.2与OpenGL渲染总结(一)Cocos2d-x3.2的渲染流程
- mac搭建cocos2d-x安卓开发环境
- cocos2d中让视角根据主角精灵移动
- cocos2dx 3.x win7+VS2012开发环境搭建及HelloWorld
- cocos2dx 3.x打包出现Can't find config file .cocos-project.json in path
- 第一篇(详解cocos2d-x中宏CC_DLL)
- cocos2d-x Tests讲解三:Particle System(粒子系统)
- c++自定义消息管理机制(类似cocos2d-x的实现方式)
- cocos2d-x sqlite的读取和相关操作
- 记录quick cocos2d-x3.2升级至cocos2d-x3.8