0

I have a simple CCLayer subclass with a circle as the background image. I also have a CCLabelTTF as a child node. How can I center the label's text on the background image?

Here's what I have:

// in MyCCLayer's init method
CCSprite *backgroundImage = [CCSprite spriteWithFile:@"circle.png"];
[self addChild:backgroundImage];
self.contentSize = backgroundImage.contentSize;

CCLabelTTF *label = [CCLabelTTF labelWithString:@"0" 
                                         dimensions:self.contentSize 
                                          alignment:UITextAlignmentCenter 
                                           fontName:@"Arial" 
                                           fontSize:32];
[self addChild:label];

I've tried changing the anchorPoint and position on the label but I can't get the text to just be centered on the background image. The text is always offset. I'd like to have centered text regardless of the font size.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

2 Answers2

2

I am assuming looking at your code that your label has ended up on the bottom of the circle? If you create the label like follows it should work for you.

CCLabelTTF *label = [CCLabelTTF labelWithString:@"0" fontName:@"Arial" fontSize:32];
label.anchorPoint = ccp(0.5, 0.5);
label.position = ccp(backgroundImage.contentSize.width/2, backgroundImage.contentSize.height/2);
Ben Trengrove
  • 8,191
  • 3
  • 40
  • 58
0
  try this code:

  CCSprite *backgroundImage = [CCSprite spriteWithFile:@"circle.png"];
  [self addChild:backgroundImage];

  backgroundImage.position=ccp(winSize.width/2,winSize.height/2);

  CCLabelTTF *label = [CCLabelTTF labelWithString:@"0" 
                                     dimensions:self.contentSize 
                                      alignment:UITextAlignmentCenter 
                                       fontName:@"Arial" 
                                       fontSize:32];
  label.position=backgroundImage.position;
  [self addChild:label];
KARTHIK RA
  • 469
  • 2
  • 8