我试图在文字变大时截断标签,而是从中心向左侧展开。
这是我的摘录。
CCLabelTTF *playerLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"Playerdadsadsd %d",i+1] fontName:@"Helvetica-Bold" fontSize:fontSize];
playerLabel.color = playerColor;
playerLabel.name = [NSString stringWithFormat:@"%d",1002+i];
playerLabel.position = ccp(playerSprite.position.x + playerSprite.contentSize.width + 10, yPos);
playerLabel.adjustsFontSizeToFit = YES;
[self addChild:playerLabel];
答案 0 :(得分:1)
我不确定您要实现的目标,但请尝试将dimensions
参数传递给init方法:
//The label won't go out of this rectangle
CGSize rect = CGSizeMake(viewSize.width * 0.1f, viewSize.height * 0.1f);
NSString *text = [NSString stringWithFormat:@"Playerdadsadsd %d",i+1];
CCLabelTTF *playerLabel = [CCLabelTTF labelWithString: text
fontName: @"Helvetica-Bold"
fontSize: fontSize
dimensions: rect]; // <-- Note this parameter
//.. the rest of your code..
答案 1 :(得分:0)
我没有在cocos2d-x中找到任何内部解决方案来截断(有或没有省略号)标签以适应指定的宽度,所以我写了一个我自己的函数。
这是在C ++中,但逻辑可以轻松复制到Objective-C
CCLabelTTF *createTruncatedLabel(const char *text, const char *fontFace, float fontSize, int width, bool useEllipsis)
{
CCLabelTTF *ttfLabel = CCLabelTTF::create(text, fontFace, fontSize, CCSizeMake(0, 0), kCCTextAlignmentLeft);
CCSize size = ttfLabel->getContentSize();
if (size.width > width)
{
int len = strlen(text);
float pc = (float)width / (float)size.width;
int newLen = (int)((float)len * pc);
size = setTruncLabel(ttfLabel, text, newLen, useEllipsis);
if (size.width > width)
{
while (size.width > width)
{
newLen--;
size = setTruncLabel(ttfLabel, text, newLen, useEllipsis);
}
}
else
{
while (size.width < width)
{
newLen++;
size = setTruncLabel(ttfLabel, text, newLen, useEllipsis);
}
if (size.width > width)
{
newLen--;
setTruncLabel(ttfLabel, text, newLen, useEllipsis);
}
}
}
return ttfLabel;
}
CCSize setTruncLabel(CCLabelTTF *ttfLabel, const char*text, int len, bool useEllipsis)
{
char newText[256] = {0};
strncpy(newText, text, len);
if (useEllipsis)
{
strcat(newText, "...");
}
ttfLabel->setString(newText);
CCSize size = ttfLabel->getContentSize();
return size;
}