Ios CCLabelTTF文本对齐
我有一个模仿按钮的类。它包含一个标签,我正试图将其水平居中对齐。无论我做什么尝试,标签都保持在左手边,这让我觉得这比看起来更复杂。以下是唯一的初始化/设置代码:Ios CCLabelTTF文本对齐,ios,cocos2d-iphone,text-alignment,cclayer,cclabelttf,Ios,Cocos2d Iphone,Text Alignment,Cclayer,Cclabelttf,我有一个模仿按钮的类。它包含一个标签,我正试图将其水平居中对齐。无论我做什么尝试,标签都保持在左手边,这让我觉得这比看起来更复杂。以下是唯一的初始化/设置代码: -(CCButtonLayer*)initWithText:(NSString*)text bgColor:(ccColor4B)color width:(GLfloat)width height:(GLfloat)height { self = [super initWithColor:color width:width he
-(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;
}
这两条线决定了标签的位置
尝试将它们设置为:
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);
我假设self是一个按钮,它的内容大小已经设置好了
这两条线决定了标签的位置
尝试将它们设置为:
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);
我假设self是按钮,它的内容大小已经设置在这一点上,正如James所说,更改主播点会影响对齐。因此,不要指定CGPointZero,因为这将使左下角与父对象的位置对齐 您仍然没有看到任何更改的事实可能表明您没有考虑标签的位置实际上是相对于父位置的偏移。现在,如果您也更改了父对象的锚点,则标签的位置将是相对于父对象左下角的偏移
长话短说:保持主播点不变。除了标签,您可以使用锚点影响对齐。正如James所说,更改锚点会影响对齐。因此,不要指定CGPointZero,因为这将使左下角与父对象的位置对齐 您仍然没有看到任何更改的事实可能表明您没有考虑标签的位置实际上是相对于父位置的偏移。现在,如果您也更改了父对象的锚点,则标签的位置将是相对于父对象左下角的偏移
长话短说:保持主播点不变。除了标签,您可以使用锚点影响对齐。我删除了标签的对齐属性,并手动对齐。很明显,我看不到有什么事情正在发生,也许有另一个偏移量,正如你所说的@learncos2d
// 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);
我删除了标签的对齐属性,改为手动对齐。很明显,我看不到有什么事情正在发生,也许有另一个偏移量,正如你所说的@learncos2d
// 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);
这里肯定还有别的事情发生。我最终用下面的方法实现了这一点。这里肯定发生了其他事情。我最终用下面的方法完成了这项工作。