How to get a suitable CGImage from a combined TIFF to display scale

I have two PNGs in a Mac project. Normal and @ 2x. Xcode combines them into one TIFF with @ 2x at index 0 and @ 1x at index 1.

What is the proposed approach for obtaining the corresponding image as a version of CGImageRef (for use with quartz) for the current display scale?

I can get the image manually through CGImageSource:

NSBundle *mainBundle = [NSBundle mainBundle]; NSURL *URL = [mainBundle URLForResource:@"Canvas-Bkgd-Tile" withExtension:@"tiff"]; CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)(URL), NULL); _patternImage = CGImageSourceCreateImageAtIndex(source, 1, NULL); // index 1 is @1x, index 0 is @2x CFRelease(source); 

I also found this to work, but I'm not sure if this will return the Retina version on the Retina display:

 NSImage *patternImage = [NSImage imageNamed:@"Canvas-Bkgd-Tile.tiff"]; _patternImage = [patternImage CGImageForProposedRect:NULL context:nil hints:nil]; CGImageRetain(_patternImage); // retain image, because NSImage goes away 

A valid answer to this question either gives a decision on how to get a CGImage from a combined TIFF with multiple permissions, or explains why the second approach works. Or what changes are needed.

+4
source share
1 answer

I prefer to answer the question "why does the second approach work here."

In a WWDC video published since 2010, they said that:

+ [NSImage imageNamed:] selects the best image view object available for the current display.

Thus, it is likely that you will call this class method from a locked focus context (for example, in the drawRect: method or similar), or perhaps you yourself call lockFocus yourself. In any case, the result is that you get the most suitable image. But only when calling + [NSImage imageNamed:] .

EDIT: Found here: http://adcdownload.apple.com//wwdc_2012/wwdc_2012_session_pdfs/session_213__introduction_to_high_resolution_on_os_x.pdf

Find the keyword "best" in the slides: "NSImage automatically selects the best view [...]."

So, your second version will return the Retina version on the Retina display, you can be sure of it, it is advertised in the documentation [*].

[*] This will only work if you provide valid illustrations.

+1
source

All Articles