Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is what happens in your code: In the first case, you just drew the layers in the graphics context of the view's underlying layer. That's what drawRect does. The origin of the frame doesn't affect that because it just positions sublayers inside their parent layer. But here, the layer is never added to the parent layer, so the origin does nothing at all and both shapes appear at 0, 0.</p> <p>In the second case, first the exact same thing happened as before, but because you also added the layers to the layer hierarchy, they got rendered again on top of the view's underlying layer, at the specified position. Each sublayer is rendered in it's own context, so the blend mode you set in drawRect has no effect on them.</p> <p>Actually you don't need sublayers at all if you just want to get an image of the two rectangles. You can draw them directly in drawRect in the view's underlying layer:</p> <pre><code>- (void)drawRect:(CGRect)rect { CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextSetBlendMode(ctx, kCGBlendModeDifference); CGContextSetFillColorWithColor(ctx, [UIColor redColor].CGColor); CGRect rect1 = CGRectMake(30, 30, 250, 200); CGContextFillRect(ctx, rect1); CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor); CGRect rect2 = CGRectMake(120, 120, 100, 250); CGContextFillRect(ctx, rect2); } </code></pre> <p>Edit (because the question was edited):</p> <p>You can use this approach for dragging layers like this:</p> <ul> <li>Draw a rectangle for each moving layer on a new layer or view on top of them, with the blend mode and drawing commands described above</li> <li>Use the current frames of the moving layers for the drawing rects</li> <li>Make sure that the new top layer doesn't receive touches</li> <li>Redraw the new layer whenever the position of an interactive layer is changed</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload