ioscocos2d-iphonetext-alignmentcclayercclabelttf

CCLabelTTF Text Alignment


I have a class which mimics a button. It contains one label, which I'm trying to align centrally (horizontally). No matter what I try, the label stays on the left hand side, leading me to think this is more complicated than it seems. Here's the only initialization/setup code:

-(CCButtonLayer*)initWithText:(NSString*)text bgColor:(ccColor4B)color width:(GLfloat)width height:(GLfloat)height {
    self = [super initWithColor:color width:width height:height];
    self.lbl = [CCLabelTTF labelWithString:text fontName:@"Marker Felt" fontSize:22];
    self.lbl.horizontalAlignment = kCCTextAlignmentCenter;
    [self.lbl setHorizontalAlignment:kCCTextAlignmentCenter];
    self.lbl.color = ccc3(0,0,0);
 //   self.lbl.contentSize = CGSizeMake(width, height); // no effect anyway
    self.lbl.anchorPoint = CGPointZero;
    self.lbl.position = CGPointZero;
    [self addChild:self.lbl];
    return self;
}

Solution

  • I removed the alignment properties of the label and aligned it manually instead. Clearly something which I can't see is happening, perhaps there's another offset as you said @LearnCocos2D

    // this worked
    CGSize textSize = [self.lbl.string sizeWithFont:[UIFont fontWithName:fontName size:fontSize]];
    self.lbl.anchorPoint = CGPointZero;
    self.lbl.position = ccp(textSize.width /2.0f, textSize.height/2.0);