Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Last active December 28, 2016 16:02
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicklockwood/493da04de6ea5cbc7a7e to your computer and use it in GitHub Desktop.
Save nicklockwood/493da04de6ea5cbc7a7e to your computer and use it in GitHub Desktop.
Animating layer contents when bounds changes
@interface AnimatedContentsLayer: CALayer
@property (nonatomic, assign) CGSize animatedSize;
@end
@implementation AnimatedContentsLayer
@dynamic animatedSize;
+ (BOOL)needsDisplayForKey:(NSString *)key
{
if ([key isEqualToString:@"animatedSize"])
{
return YES;
}
return [super needsDisplayForKey:key];
}
- (void)display
{
CGSize size = ((AnimatedContentsLayer *)self.presentationLayer).animatedSize;
UIGraphicsBeginImageContext(size);
[[UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1] setFill];
UIRectFill((CGRect){CGPointZero, size});
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.contents = (id)image.CGImage;
}
- (void)setBounds:(CGRect)bounds
{
super.bounds = bounds;
self.animatedSize = bounds.size;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment