views:

989

answers:

2

Hey there,

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

+1  A: 

The contents of the topmost (in this case, last added) subview will appear in front of all other views. If you add an image subview and draw into its parent view, the image will appear in front of any drawing you do in that parent view.

You should draw into a new view you add to the main view only after adding the UIImageView.

You could also use bringSubviewToFront: and sendSubviewToBack: to manually reorder views if you need to.

(From your post, it's unclear which view you're drawing into, but I assume you're drawing into that main parent view which would explain this behavior.)

PCheese
Thanks for the order (ToFront/ToBack).I am still stuck with the fact that lines/path is drawn before the UIImageView, hence is not visible at their location
Adi
+1  A: 

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:
unforgiven