Objective-c – How to set order of display in Objective-C

iphoneobjective cquartz-graphics

I'm trying to mix between UIImageView drawing and line drawing using CGContext path draw commands, but the draw order is not correct.
I need to draw the path on top of the images but get the reverse.

The way I implemented it:

  1. Setting UIImage within a UIImageView and adding the UIImageView as a subview of the main view.
  2. Next I use the 'drawRect' (refresh draw function) to draw the path using the UIKit CGContextStrokePath function.

Now, other than using the Context image draw function directly (I want to avoid that because I reuse my image resources by several UIImageViews), is there a way to set the order correctly (a flag set maybe)?

The problem again is that lines/path are drawn before the UIImageViews (which are drawn automatically via the connection to the parent UIView), hence they are not visible over the images / UIImageViews.

Thanks

Best Answer

You can try implementing this through Quartz Core using layers (see the CALayer class documentation). Basically, you can have layers hierarchies. You associate each UIView to a different layer, then the layers are rendered together providing a single, composite layer. Besides, you can also apply transforms and animations to layers.

You need to import the QuartzCore header and do something like

#import <QuartzCore/QuartzCore.h>
UIView *mainView = [[UIView alloc] initWithFrame...
UIImageView *imageView = ...

CaLayer *mainViewLayer = mainView.layer;
[mainViewLayer addSubLayer: imageView.layer];

Then, when mainView appears on the screen, all the sublayers are merged together and rendered on screen. What happens is that each view renders its layer, while mainViewLayer is rendered merging together the two layers.

Let me know if this works for you.

You can have as many layers as you like. You can create an arbitrary hierarchi by using the CALayer methods

– addSublayer: 
– removeFromSuperlayer
– insertSublayer:atIndex:
– insertSublayer:below:
– insertSublayer:above:
– replaceSublayer:with: