Search code examples
iphoneobjective-ccocoaioscore-animation

Aligning Background Within a CALayer


I'm trying to create a UIImage from an image context and set that as the contents of a CALayer (the image will end up split up and spread across multiple CALayers). The only problem is, it doesn't seem to be aligning correctly - it's offset by 30 pixels or so.

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {

        number = 1;

        background = [UIImage imageNamed:@"numberBackground.png"];

        // draw images
        UIGraphicsBeginImageContext(CGSizeMake(background.size.width, background.size.height));

        [background drawAtPoint:CGPointMake(0, 0)];

        NSString *numberString = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%d", number]];
        [[UIColor whiteColor] set];
        [numberString drawAtPoint:CGPointMake(0, 0) withFont:[UIFont fontWithName:@"HelveticaNeue" size:128]];

        UIImage *front = [UIGraphicsGetImageFromCurrentImageContext() retain];

        UIGraphicsEndImageContext();

        // top layer
        topLayer = [CALayer layer];
        [topLayer setContents:(id)front.CGImage];
        [topLayer setContentsGravity:@"kCAGravityTop"];
        [topLayer setFrame:CGRectMake(0, 0, background.size.width, background.size.height / 2)];
        [topLayer setAnchorPoint:CGPointMake(0, 1)];
        [topLayer setPosition:CGPointMake(0, background.size.height / 2)];
        [topLayer setMasksToBounds:NO];
        [topLayer setBackgroundColor:[UIColor lightGrayColor].CGColor];
        [self.layer addSublayer:topLayer];

    }
    return self;
}

I don't have enough reputation points to post an image yet, but here's how the layer renders, as well as how it should render and the full image: link text


Solution

  • Found my mistake - setContentsGravity should take the built-in string constant kCAGravityTop, not my NSString literal @"kCAGravityTop".