Skip to content

Instantly share code, notes, and snippets.

@smokyonion
Created March 12, 2013 22:14
Show Gist options
  • Save smokyonion/5147584 to your computer and use it in GitHub Desktop.
Save smokyonion/5147584 to your computer and use it in GitHub Desktop.
Layer backed NSView with Retina support
@interface VWLayerBackedBaseView : NSView
@end
@interface VWLayerBackedBaseView ()
- (void)_updateContentScale;
@end
@implementation VWLayerBackedBaseView
#pragma mark Retina Display Support
- (void)_updateContentScale
{
if (![self window]) return;
CALayer *layer = self.layer;
if ([layer respondsToSelector:@selector(contentsScale)]) {
CGFloat scale = [(id)[self window] backingScaleFactor];
[(id)self.layer setContentsScale:scale];
// If this instance holds any other CALayers, set their contents scale here
// ...
}
}
- (void)scaleDidChange:(NSNotification *)n
{
[self _updateContentScale];
}
- (void)viewDidMoveToWindow
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(scaleDidChange:)
name:@"NSWindowDidChangeBackingPropertiesNotification"
object:[self window]];
// immediately update scale after the view has been added to a window
[self _updateContentScale];
}
- (void)removeFromSuperview
{
[super removeFromSuperview];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NSWindowDidChangeBackingPropertiesNotification" object:[self window]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment