Thursday, August 9, 2012

How to center a CCLabel when scaled

This is simple math, but it took me a while to figure out why my CCLabelBMFont wasn't being centered on its anchor point like it normally does.  Cocos2d has a default anchor point of (0.5,0.5).  So when you create a CCLabel at point A, the center of the label will be at point A.  This all changes when you scale the label though.

The contentSize is what the label is centered on.  So if you have a label that's 100 points wide and you scale it 50%, the contentSize is still 100 points wide, but your text is only maybe 50 points wide.  The starting point for the text is also the same as when the label was at 100%.  So to center your label, you'll have to add to the X coordinate like so:


        CCLabelBMFont* l = [CCLabelBMFont labelWithString:@"Some Text" fntFile:@"Helvetica.fnt"];        
        l.scale = 0.3;
        float scaledWidth = l.contentSize.width * l.scale;
        float difference = (l.contentSize.width - scaledWidth)/2;
        l.position = ccp(c + difference, 100);

2 comments:

  1. HI ! i got my solution from your blog. it was working for me after some modification. Thanks For Sharing.

    ReplyDelete
  2. Can you give me more suggestion regarding this, this code is working very well, but needs more solutions regarding CCLabel. Thanks for the article…Keep Sharing…!

    ReplyDelete