6

According to the Mac Dev Center docs, you should be able to set the contents property of a CALayer and have that render automatically. However, I still can't get a simple image to show up by adding a sublayer to the UIView's root later. I've tried multiple different variations; here's what I have so far:

(Note: I know there are other ways of rendering images; for my purposes I'd like to use CALayer's for some of the more complicated stuff I'm going to get into).

(in viewDidDisplay() of the ViewController):

 CALayer *theLayer = [CALayer layer];
 [[[self view] layer] addSublayer:theLayer];
 theLayer.contents = (id)[[UIImage imageNamed:@"mypic.png"] CGImage];
 theLayer.contentsRect = CGRectMake(0.0f, 0.0f, 300.0f, 300.0f);
 theLayer.bounds = CGRectMake(0.0f, 0.0f, 300.0f, 400.0f);

Anyone know what I'm doing wrong?

Thanks!

  • Thank you Ben - you got it. My problem was the contentsRect was way too big - didn't realize it was a unit coordindate space. Interestingly, the image is placed high and to the left (I only see the lower right 1/4 of it) - I'm having to adjust the position to get the top left corner of the image to sit in the top-right corner of the screen. Thanks! –  Dec 24 '09 at 14:25

3 Answers3

5

You could load the image into a UIImageView, which is decended from UIView and therefore has it's own layer property.

UIImageView *imgView = [[UIImageView alloc] initWithFrame:frame];
imgView.image = [UIImage imageNamed:@"mypic.png"];

[[[self view] layer] addSublayer:[imgView layer]];
[imgView release];
imnk
  • 4,342
  • 3
  • 29
  • 31
1

You don't need to set the contentsRect (and if you do, it should be in the unit coordinate space, probably just CGRectMake(0, 0, 1.0, 1.0).

You might want to set the layer's position property.

Midhun MP
  • 103,496
  • 31
  • 153
  • 200
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
0

You need to create two CALayer . This is perfect way to display the image within the CALayer.

CALayer *pulseLayer_ = [[CALayer layer] retain];

pulseLayer_.backgroundColor = [[UIColor whiteColor] CGColor];
pulseLayer_.bounds = CGRectMake(0., 0., 80., 80.);
pulseLayer_.cornerRadius = 12.;
pulseLayer_.position = self.view.center;

[self.view.layer addSublayer:pulseLayer_];


CALayer *imageLayer = [CALayer layer];

imageLayer.frame = pulseLayer_.bounds;
imageLayer.cornerRadius = 10.0;
imageLayer.contents = (id) [UIImage imageNamed:@"jacklogo.png"].CGImage;
imageLayer.masksToBounds = YES;

[pulseLayer_ addSublayer:imageLayer];

[pulseLayer_ setNeedsDisplay];

I think its make solution to your problem.

Arunjack
  • 621
  • 1
  • 6
  • 4