2012-08-18 98 views
1

我有一个模仿按钮的类。它包含一个标签,我试图集中对齐(水平)。无论我尝试什么,标签都留在左手边,这让我觉得这比看起来更复杂。这是唯一的初始化/设置代码:CCLabelTTF文本对齐

-(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; 
} 

回答

3

我删除了标签的对齐属性并手动将其对齐。很明显,我看不到的东西正在发生,或许还有另一个偏移,正如你所说@ 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); 
1
self.lbl.anchorPoint = CGPointZero; 
self.lbl.position = CGPointZero; 

这是这是决定你的标签的位置这两条线。

尽量将它们设置为:

self.lbl.anchorPoint = ccp(0.5, 0.5); //This is default, you could omit 
self.lbl.position = ccp(self.contentSize.width/2.0f, self.contentSize.height/2.0f); 

我假设“自我”是按钮,并且它的内容的大小已设置在该点

+0

不幸的是没有效果。 – Echilon 2012-08-18 18:42:15

+0

那个时候什么是'self.contentSize'? – 2012-08-18 18:50:41

1

正如詹姆斯所说,改变anchorPoint影响对准。所以不要指定CGPointZero,因为这会将左下角与父母的位置对齐。

你还没有看到变化的事实可能表明你没有考虑到标签的位置实际上是对父母位置的偏移。现在,如果您也更改了父级的anchorPoint,则标签的位置将是父级左下角的偏移量。

长话短说:保持锚点不变。除了标签之外,您可以使用anchorPoint来影响对齐。

+0

这里绝对有其他事情发生。我最终使用下面的方法得到了这个工作。 – Echilon 2012-08-19 14:36:41