Search code examples
objective-cdeprecatednsimage

NSImage Deprecated method: setFlipped replacement


In the docs, https://developer.apple.com/library/mac/documentation/cocoa/reference/applicationkit/classes/NSImage_Class/DeprecationAppendix/AppendixADeprecatedAPI.html#jumpTo_17

It says setFlipped should be replaced with drawInRect -- but after looking through several examples and many failed attempts, I can't get my image to draw flipped using the arguments that are passed into drawInRect

Does anybody have experience, or know how to flip an image with the drawInRect method? Or is there a different way?

Thanks in advance!


Solution

  • The deprecation explanation was written with the expectation that -setFlipped: was being used to compensate for drawing right-side-up into a flipped view. That doesn't correspond to your use case where you're apparently trying to draw it upside-down, so the explanation doesn't help.

    To draw upside-down, you should adjust the graphics context's transform using NSAffineTransform. The docs have a discussion of creating a flip transform to flip with respect to the whole view, but then you have to figure where to draw relative to that flipped coordinate system. I think it's easier to just translate the origin to the top-left of the destination rectangle, scale the Y direction by -1, then draw at (0, 0).

    [NSGraphicsContext saveGraphicsState];
    
    NSAffineTransform* xform = [NSAffineTransform transform];
    [xform translateXBy:NSMaxX(destRect) yBy:NSMinY(destRect)];
    [xform scaleXBy:1 yBy:-1];
    [xform concat];
    
    [image drawInRect:NSMakeRect(0, 0, NSWidth(destRect), NSHeight(destRect))];
    
    [NSGraphicsContext restoreGraphicsState];