Archive for February, 2009

Drawing with layers on the iPhone

I’m currently giving myself some time to discover the iPhone’s SDK. Wanting to have some fun with it, I’m playing with the graphical Cocoa engine, Quartz.

Liking the layer concept each time I see it (in particular in picture edition software), I dive into the CALayer class description and associated concept. For my newbie’s eyes, using layers may just be the same as using views. However, I have found somewhere on the net it may be faster (in performance terms) to use layers than views. So I give them a try!

Seeming quite simple in theory, I have had a very hard time to get my layers displayed. I will not come back on the whole theory here (you can find it just like I did in the Apple’s documentation), however, you may soon face the same solid wall as me. It kept me several hours, but since I got over it, I’ll give you my advice on this…

My goal was quite simple:

  1. adding a layer to the UIView’s default layer,
  2. trying to draw a picture in this layer (in fact, drawing anything would have been alright…).

Adding a sublayer was no problem, defining the methods to draw inside neither (well documented in Apple’s documentation). However, I could not have it drawn. And I hardly found code helping me on this: Apple’s one seems to be more on Mac’s Cocoa than on iPhone’s at the moment, and not much help was found on the net. I finally found an question/answer that almost matched my case, and I found the answer:

When you want to display your sublayer, don’t ask the view owning the main layer to redraw (with setNeedsDisplay), ask the main layer!

@interface MyView : UIView {}

@implementation MyView
- (void)setupLayers {
CALayer *mySublayer = [CALayer layer];
mySublayer.delegate = aDelegate;
[self.layer addSublayer:mySublayer];
[self.layer setNeedsDisplay];

This is just a simple tip, but I hope it may save some problems to some of you. If you see an error or want to comment, do not hesitate!

[EDIT] Hey, you know what? Finally that may not have been the problem (neither the solution) at all! In fact this post is now too old, I am not going to give another try, but in my recent developing, I think I faced the same problem. So I looked here, hoping I had already wroten on the solution (long time ago, not so good memory…). In fact I had, but my own solution didn’t work that time 😦 Finally, the whole problem may just have been the layer’s size! Check it before looking further: it may well be 0x0… in which case there is no surprise it won’t display anything!

%d bloggers like this: