Anchor Point of CALayer questions... Bronze


#1

So I have an odd problem that I’m not quite sure why. To my understanding (and from the API for Xcode) it is noted that by default, the anchor point for a CALayer is 0.5 0.5 or the dead center of the CALayer before it. My question is, why does this not hold true for the CALayer the book had us create? For some reason, the defaulted anchor point was the upper left hand corner of the current CALayer. I had to change my anchor point to (-0.5, -0.5) to center my new Layer as shown below. Why is this? Why couldn’t I also use the position for the boxLayer? I’m already a little confused on differentiating between pixel locations (actual CGPoints) and percentage locations (such as 0.5 and 0.5 being %50 of the height and width). This just confused me lol.

myLayer = [[CALayer alloc]init]; [myLayer setBounds:CGRectMake(0.0, 0.0, [boxLayer bounds].size.width /2, [boxLayer bounds].size.height /2)]; //[myLayer setPosition:[boxLayer position]]; [myLayer setAnchorPoint:CGPointMake(-0.5, -0.5)]; //this centers the image at all times UIImage *imageLayer = [UIImage imageNamed:@"TEALogoSprite.png"]; CGImageRef myImage = [imageLayer CGImage]; [myLayer setContents:(__bridge id)myImage]; [myLayer setContentsGravity:kCAGravityResizeAspect]; [boxLayer addSublayer:myLayer];


#2

This reply is too late for the original poster, but in case someone else had this problem…

The position property for a layer is in the coordinate space of the superlayer. The position of boxLayer is in the coordinate space of [self layer]. But you’re adding the half-sized box as a sublayer of boxLayer so its position is in the coordinate space within boxLayer – the center of which is (85/2.0, 85/2.0):

Sure, dividing the bounds property by 2 would have been more bombproof.


#3

That doesn’t answer the original question about the anchor point. I’m having the same issue.


#4

You should be using position, not anchor to position the sublayer. If you draw the sublayer with the default anchor, you’ll see that the center of the rectangle sits at postion 0,0 of the parent layer. If the original boxLayer’s position was 0,0, you’d see it setting on the top left corner of the screen with it’s center at 0,0 of the view (or [self layer] in this case). Try it!

While changing the anchor does get you to the same place, if you had to perform a rotation, you’d no longer be rotating around the center of the sublayer as you’ve moved it’s anchor.