RobertJoseph
RobertJoseph

Reputation: 8158

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;
}

Upvotes: 0

Views: 1351

Answers (1)

Jonathan Cichon
Jonathan Cichon

Reputation: 4406

either set the correct anchorpoints, or use

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

instead of

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

Upvotes: 2

Related Questions