Evil Nodoer
Evil Nodoer

Reputation: 1957

CALayer's image not showing up

I am trying to use CALayer to display an image, but the image is not showing up. I've verified that 'image' is not nil, image.size is correct, and layer.contents is a valid CABackingStore.

- (void)viewDidLoad
{
  [super viewDidLoad];

  layer = [[CALayer alloc] init];
  [self.view.layer addSublayer:layer];
  UIImage *image = [UIImage imageNamed:@"download.jpeg"];
  layer.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
  layer.position = self.view.center;
  layer.contents = (id)image.CGImage;

  [layer setNeedsDisplay];
}

What could be the problem here?

Upvotes: 2

Views: 2657

Answers (2)

Brian Nickel
Brian Nickel

Reputation: 27560

Removing [layer setNeedsDisplay]; should correct the behavior.

From the docs (emphasis added):

Calling this method causes the layer to recache its content. This results in the layer potentially calling either the displayLayer: or drawLayer:inContext: method of its delegate. The existing content in the layer’s contents property is removed to make way for the new content.

Upvotes: 5

9to5ios
9to5ios

Reputation: 5555

either use this

layer = [[CALayer alloc] init];
  [self.view.layer addSublayer:layer];

  //UIImage *image = [UIImage imageNamed:@"download.jpeg"];
  layer.bounds = CGRectMake(0, 0, 300,300);
  layer.position = self.view.center;
  //layer.contents = (id)image.CGImage;
    layer.contents = (id)[UIImage imageNamed:@"download.jpeg"].CGImage;
    [layer setNeedsDisplay];

or

remove [layer setNeedsDisplay]; I guess the setNeedsDisplay made the layer to redraw the content and so deleting the image.

--

Upvotes: 0

Related Questions