Search code examples
iosuiviewcore-animationcalayercaanimation

Cannot get CALayer to display in UIView


I have a simple, single-view app and for some reason I cannot get a CALayer to display in the app's UIView. The background color of the view is correct but the image in the CALayer is not visible. I've stepped through the code in the debugger and I'm sure that the image is being loaded correctly. If instead of using a CALayer I use a UIImageView everything works as you'd expect.

Here is the code from my UIViewController subclass. Do you see what I'm doing wrong?

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor darkGrayColor];

    CALayer* cardLayer = [self layerForCard];

    [self.view.layer addSublayer:cardLayer];
}

- (CALayer *)layerForCard
{
    UIImage* cardImage = [UIImage imageNamed:@"card1.jpg"];
    CGSize cardSize    = cardImage.size;
    CGRect cardRect    = CGRectMake(.0, .0, cardSize.width, cardSize.height);

    // Container Layer
    CALayer *containerLayer = [CALayer layer];
    containerLayer.bounds   = cardRect;
    containerLayer.opacity  = 1.0;

    // Image Layer
    CALayer *imageLayer = [CALayer layer];
    imageLayer.bounds = cardRect;
    imageLayer.contentsGravity = kCAGravityResizeAspectFill;
    imageLayer.contents = CFBridgingRelease(cardImage.CGImage);

    [containerLayer addSublayer:imageLayer];

    return containerLayer;
}

Solution

  • either set the correct anchorpoints, or use

    containerLayer.frame = cardRect;
    ..
    imageLayer.frame = cardRect;
    

    instead of

    containerLayer.bounds = cardRect;
    ..
    imageLayer.bounds = cardRect;