Created
November 11, 2014 20:54
-
-
Save beefon/0f10ff78285015df9dbd to your computer and use it in GitHub Desktop.
This small sample shows you the difference between CoreAnimation and timer-based animations. Whenever main thread is blocked, timer-based animation stutters, while CA continues to render. More info https://medium.com/@beefon
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 ViewController () | |
@property (nonatomic, strong) UIView *caView; | |
@property (nonatomic, strong) UIView *timerView; | |
@property (nonatomic, assign) NSTimeInterval start; | |
@end | |
@implementation ViewController | |
static CGFloat const kDuration = 2.0; | |
- (void)viewDidLoad | |
{ | |
[super viewDidLoad]; | |
self.caView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]; | |
self.caView.backgroundColor = [UIColor orangeColor]; | |
[self.view addSubview:self.caView]; | |
self.timerView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.view.bounds) - 100 - 50, 50, 100, 100)]; | |
self.timerView.backgroundColor = [UIColor blueColor]; | |
[self.view addSubview:self.timerView]; | |
[self performSelector:@selector(repeatedlyBlockMainThread) withObject:nil afterDelay:3]; | |
} | |
- (void)viewDidAppear:(BOOL)animated | |
{ | |
[super viewDidAppear:animated]; | |
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; | |
anim.toValue = @(M_PI); | |
anim.duration = kDuration; | |
anim.repeatCount = 500; | |
[self.caView.layer addAnimation:anim forKey:@"anim"]; | |
CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkFire:)]; | |
[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; | |
self.start = CACurrentMediaTime(); | |
} | |
- (void)displayLinkFire:(CADisplayLink *)sender | |
{ | |
CGFloat progress = (sender.timestamp - self.start)/kDuration; | |
CGAffineTransform t = CGAffineTransformMakeRotation(progress * M_PI); | |
self.timerView.transform = t; | |
} | |
- (void)repeatedlyBlockMainThread | |
{ | |
NSLog(@"blocking main thread!"); | |
[NSThread sleepForTimeInterval:0.25]; | |
[self performSelector:@selector(repeatedlyBlockMainThread) withObject:nil afterDelay:1]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment