Reputation: 2927
i am trying to truncate label when text becomes large but instead it got expanded from center moving to left side.
This is my snippet.
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];
Upvotes: 0
Views: 435
Reputation: 308
I didn't find any intrinsic solution in cocos2d-x for truncating (with or without ellipsis) a label to fit in a specified width, so I wrote a function of my own.
This is in C++, but the logic can be copied easily to 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;
}
Upvotes: 0
Reputation: 3384
I'm not sure what are you trying to achieve, but try passing dimensions
parameter to the init method:
//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..
Upvotes: 1