How to get real size of a CCLabelTTF in cocos2d? - cocos2d-iphone

I have a CCLabelTTF with a dynamic text. Let's say it has a maxsize of 200,200. I create it:
CCLabelTTF * label = [CCLabelTTF labelWithString:#"Hello!" dimensions:CGSizeMake(200,200) alignment:UITextAlignmentLeft lineBreakMode:UILineBreakModeWordWrap fontName:#"Helvetica" fontSize:15];
This works nicely.
But I have to put something right under, therefore I need to know the height of the text. I've tried label.texture.contentSize, label.contentSize. They both is 200,200.
What can I do here?
I'm using cocos2d 1.x

You can use NSString's sizeWithFont methods.
NSString *hello = #"Hello!"
UIFont *font = ...
CGSize *textSize = [hello sizeWithFont:font constrainedToSize:CGSizeMake(200, 200) lineBreakMode:UILineBreakModeWordWrap];
This should tell you the exact size of the text.

UIFont * font = [UIFont fontWithName:#"HelveticaNeue" size:15];
CGSize realSize = [message sizeWithFont:font constrainedToSize:CGSizeMake(210, 200) lineBreakMode:UILineBreakModeWordWrap];
label = [CCLabelTTF labelWithString:message dimensions:realSize alignment:UITextAlignmentCenter lineBreakMode:UILineBreakModeWordWrap fontName:#"HelveticaNeue" fontSize:15];
This is what I ended up doing based on #Ben answer. It works perfectly!

Related

Get Content Size of string

Is it possible to get content size of a string in c++. I'm not talking about length here. I want to place strings in a row one after the other, say on a label but don't want to get content size of label.I need to get space a string covers on screen.
What you ask is not possible with C++ string.
May be you could use something like this, with NSString and sizeWithFont:
NSString *str= #"Hello, World!"
UIFont * font = [UIFont fontWithName:#"YourFontName" size:11];
CGSize supposedSize = [str sizeWithFont:font constrainedToSize:CGSizeMake(100, 100)];
CCLabelTTF *label = [CCLabelTTF labelWithString:str dimensions:supposedSize fontName:#"YourFontName" fontSize:11];
to find out the height and width of the text in cocos2d.

Cocos2D CCButton setBackgroundColor not working

I added the following code to the Cocos2D default template's IntroScene:
CCButton *playButton = [CCButton buttonWithTitle:#"Play" fontName:#"HelveticaNeue" fontSize:18.0f];
[playButton setBackgroundColor:[CCColor colorWithWhite:0.7f alpha:1.0f] forState:CCControlStateNormal];
[playButton setBackgroundColor:[CCColor colorWithWhite:0.75f alpha:1.0f] forState:CCControlStateHighlighted];
playButton.positionType = CCPositionTypeNormalized;
playButton.position = ccp(0.5f, 0.35f);
playButton.zoomWhenHighlighted = NO;
playButton.preferredSize = CGSizeMake(222, 46);
[playButton setTarget:self selector:#selector(onSpinningClicked:)];
[self addChild:playButton];
For some reason the button has no background color. Any ideas?
Because you didn't set a color, only brightness (this is what "white" means in the context of CCColor).
Try using a color with this initializer:
CCColor* normalColor = [CCColor colorWithRed:1.0 green:0.0 blue:0.0 alpha:1.0f]
[playButton setBackgroundColor:normalColor forState:CCControlStateNormal];
This will make the button background red.

RIght-align and position a CCLabelTTF

I would expect the following code to position the label at the upper right of the screen. However the x position appears off to the right of the screen and I have to manually move it way over. What is wrong with this code?
CGSize winSize = [[CCDirector sharedDirector] winSize];
self.screenTop = winSize.height;
self.screenRight = winSize.width;
self.screenBottom = 0;
self.screenLeft = 0;
self.scoreLabel = [CCLabelTTF labelWithString:#"000000" dimensions:CGSizeMake(200,30) hAlignment:kCCTextAlignmentRight fontName:#"Helvetica" fontSize:24];
self.scoreLabel.position = ccp(self.screenRight - 20, self.screenTop - 20);
[self addChild:self.scoreLabel z:1];
The position is logged correctly as {548, 300} (iPhone5). It appears that hAlignment:kCCTextAlignmentRight doesn't work right.
self.scoreLabel.position = ccp(self.screenRight - 100, self.screenTop - 20);
more generically :
self.scoreLabel.position = ccp(self.screenRight - self.scoreLabel.contenSize.width/2,
self.screenTop - self.scoreLabel.contenSize.height/2);

Setting CCLabelTTF's width by getting the NSSting's text width is not working fine?

I am a iphone game developer. Right now i am developing a book app for children. For that i need to change the color of the cclabel to change word by word with a voice dictating the text in the background. To make it work as a initial process
NSString *pstring1 = #"The moon is a big eye";
int ix = 600,iy = 300;
NSArray *str1 = [pstring1 componentsSeparatedByString:#" "];
NSLog(#"str1 %#",str1);
for(NSString* st in str1)
{
CCLOG(#"STRING IS %# POSITION IS %d",st,ix);
CGFloat wid= 0;
CGFloat ss = [st sizeWithFont: [UIFont systemFontOfSize:25]].width;
wid = ss+(ss/10);
CCLabelTTF * labels = [CCLabelTTF labelWithString:st fontName:#"Marker Felt" fontSize:25 ];
[labels setPosition:CGPointMake(ix, iy)];
[labels setColor:ccBLUE];
ix+=wid+5;
[self addChild:labels];
For example i separated a string with white space and added it to an NSArray. And in the for loop i am getting the text width of the string in the array one by one using sizeWithFont and i have added it as CGFloat value.And i am creating cclabel for each word in the array and incrementing the width size according the word's width in the array which is saved in the CGFloat. The problem is there is more white space between each cclabel or it merges with one another.I don't know whether i am correct or wrong The output looks like this http://screencast.com/t/p8Rj8GKZ . Please help me to sort out this issue. If this is issue is sorted out means i will use timer and change the color of the each cclabel to show the word to word color change effect.
Finally i fixed the issue which i have mentioned above
I have just set the contentsize of the label to zero and now all the unwanted white space between the one word to the another got disappeared
[labels setContentSize:CGSizeZero];

cocos2d-x convert UIImage to CCSprite

has anyone an idea how to convert a UIImage to cocos2d-x CCSprite.
My latest attempt was was:
1. Store the UIImage as png on the phone
2. Load the png as a CCSprite
[UIImagePNGRepresentation(photo) writeToFile:imagePath atomically:true];
CCSprite *sprite = CCSprite::spriteWithFile(imagePath);
But this crashed in CCObject retain function
void CCObject::retain(void)
{
CCAssert(m_uReference > 0, "reference count should greater than 0");
++m_uReference;
}
And I do not understand how Walzer Wangs suggestion works
http://cocos2d-x.org/boards/6/topics/3922
CCImage::initWithImageData(void* pData, int nDataLen, ...)
CCTexture2D::initWithImage(CCImage* uiImage);
CCSprite::initWithTexture(CCTexture2D* pTexture);
CCSprite* getCCSpriteFromUIImage(UIImage *photo) {
CCImage *imf =new CCImage();
NSData *imgData = UIImagePNGRepresentation(photo);
NSUInteger len = [imgData length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [imgData bytes], len);
imf->initWithImageData(byteData,imgData.length);
imf->autorelease();
CCTexture2D* pTexture = new CCTexture2D();
pTexture->initWithImage(imf);
pTexture->autorelease();
CCSprite *sprit = new CCSprite();
sprit->createWithTexture(pTexture);
sprit->autorelease();
DebugLog("size :%f :%f ",sprit->getContentSize().width , sprit->getContentSize().height);
return sprit;
}
I got the solution for my own Problem. You can't create a CCSprite before the CCDirector is initialized. There are missing some config settings and cocos releases the image right after it is instantiated.
Save uiimage to documents directory first
now get it using getWritablePath
Texture2D* newTexture2D = new Texture2D();
Image* JpgImage = new Image();
JpgImage->initWithImageFile("your image path.jpg");
newTexture2D->initWithData(JpgImage->getData(),JpgImage->getDataLen(),Texture2D::PixelFormat::RGB888,JpgImage->getWidth(),JpgImage->getHeight(),Size(JpgImage->getWidth(),JpgImage->getHeight()));