Created
April 2, 2014 17:02
-
-
Save levinunnink/9938385 to your computer and use it in GitHub Desktop.
NSImage retina detection category
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSImage+Retina.h | |
// | |
// Created by Levi Nunnink on 3/11/14. | |
// | |
#import <Cocoa/Cocoa.h> | |
@interface NSImage (Retina) | |
- (BOOL)hasRetina; | |
- (float)backingScaleForRepresentation:(NSBitmapImageRep*)rep; | |
- (NSBitmapImageRep*)representationForBackingScale:(float)backingScale; | |
- (NSBitmapImageRep*)retinaRep; | |
- (NSBitmapImageRep*)standardRep; | |
- (NSImage*)retinaImage; | |
- (NSImage*)standardImage; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSImage+Retina.m | |
// | |
// Created by Levi Nunnink on 3/11/14. | |
// | |
#import "NSImage+Retina.h" | |
@implementation NSImage (Retina) | |
- (BOOL)hasRetina | |
{ | |
return [self representationForBackingScale:2.0] != nil; | |
} | |
- (float)backingScaleForRepresentation:(NSBitmapImageRep*)rep | |
{ | |
return rep.pixelsWide / rep.size.width; | |
} | |
- (NSBitmapImageRep*)representationForBackingScale:(float)backingScale | |
{ | |
NSInteger backingScaleRounded = roundf(backingScale * 100); | |
for(NSBitmapImageRep *rep in [self representations]){ | |
NSInteger repBackingScaleRounded = roundf((rep.pixelsWide / rep.size.width) * 100); | |
if (backingScaleRounded == repBackingScaleRounded) { | |
return rep; | |
} | |
} | |
return nil; | |
} | |
- (NSBitmapImageRep*)retinaRep | |
{ | |
return [self representationForBackingScale:2.0]; | |
} | |
- (NSBitmapImageRep*)standardRep | |
{ | |
return [self representationForBackingScale:1.0]; | |
} | |
- (NSImage*)retinaImage | |
{ | |
NSBitmapImageRep *rep = [self representationForBackingScale:2.0]; | |
if (rep) { | |
NSImage *img = [[NSImage alloc] initWithSize:rep.size]; | |
[img addRepresentation:rep]; | |
return img; | |
} | |
return nil; | |
} | |
- (NSImage*)standardImage | |
{ | |
NSBitmapImageRep *rep = [self representationForBackingScale:1.0]; | |
if (rep) { | |
NSImage *img = [[NSImage alloc] initWithSize:rep.size]; | |
[img addRepresentation:rep]; | |
return img; | |
} | |
return nil; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment