Hypno.png flips over when drawLayer:inContext: called


I’ve successfully completed the Challenge: Dynamic Layer Content, except for one thing. When the app first launches, the Hypno.png image appears right side up, but as soon as I move the layer anywhere, it flips vertically and stays upside down. It doesn’t flip back and forth on successive touches, it just stays inverted.

Here’s my code for drawLayer:inContext:.

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
    CGFloat alpha = 1.0 - [layer position].y / 410.0;
    if (alpha > 1.0) {
        alpha = 1.0;
    else if (alpha < 0.0) {
        alpha = 0.0;
    UIImage *layerImage = [UIImage imageNamed:@"Hypno.png"];
    CGRect boundingBox = CGContextGetClipBoundingBox(ctx);
    CGContextSetAlpha(ctx, alpha);
    CGContextDrawImage(ctx, boundingBox, [layerImage CGImage]);

It does what it’s supposed to do in terms of fading the image in and out depending on the layer’s vertical position. I can’t figure out, though, why it’s flipping Hypno.png over. Any help is much appreciated.


Blimey - you’ve got good eyes ! I had to change the image to the Time.png to see what you meant.

I’m not 100% sure why this is happening - I think it’s something to do with Mac and iOS using different coordinate systems and some functions adopt the Mac convention and others adopt the iOS convention.

to fix the problem you can add the following before drawing the image in the delegate.

CGContextTranslateCTM(ctx, 0, boundingBox.size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextDrawImage(ctx, boundingBox, [layerImage CGImage]);



Thanks, Gareth, that did the trick. After looking up those two functions in the documentation, I can see that they’re re-setting the origin of the coordinate axes and then inverting the y-axis, and so it makes sense how that would fix the problem. I must admit, though, that without understanding why this is necessary, it feels a little like a hack. I guess I need to better understand how the coordinate systems differ between views and layers (or perhaps even that’s not the issue).



Agreed - it feels a bit messy but you’ll find it a common pattern - Apple use it in their QuartzDemo sample project.

It gets worse when you use this to display images from the camera - you need to allow for the orientation that the picture was taken in before working out the transform required.

Also if you are using shadows and need to support iOS versions from 3.1 and above have a look at this http://developer.apple.com/library/ios/#qa/qa1706/_index.html

code around that and it makes you feel dirty :blush: