Last active
December 28, 2016 16:02
-
-
Save nicklockwood/493da04de6ea5cbc7a7e to your computer and use it in GitHub Desktop.
Animating layer contents when bounds changes
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
@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