使用CADisplayLink實現果凍效果動畫(學習於Glow 技術團隊),cadisplaylinkglow
使用CADisplayLink實現果凍效果動畫
CADisplayLink object is a timer object that allows your application to synchronize its drawing to the refresh rate of the display.
github
1.定義一個View@interfaceJellyView()
@property (strong,nonatomic)CADisplayLink *displayLink;
@property (nonatomic)CGFloat from;
@property (nonatomic)CGFloat to;
@property (nonatomic)BOOL animating;@end
2.繪製View及移動路徑- (void)drawRect:(CGRect)rect {
CALayer *layer =self.layer.presentationLayer;
CGFloat progress =1;
if (!self.animating) {
progress = 1;
} else {
progress = 1 - (layer.position.y - self.to) / (self.from - self.to);
}
CGFloat height =CGRectGetHeight(rect);
CGFloat deltaHeight = height /2 * (0.5 -fabs(progress -0.5));
CGPoint topLeft =CGPointMake(0, deltaHeight);
CGPoint topRight =CGPointMake(CGRectGetWidth(rect), deltaHeight);
CGPoint bottomLeft =CGPointMake(0, height);
CGPoint bottomRight =CGPointMake(CGRectGetWidth(rect), height);
UIBezierPath* path = [UIBezierPathbezierPath];
[[UIColorblueColor]setFill];
[path moveToPoint:topLeft];
[path addQuadCurveToPoint:topRightcontrolPoint:CGPointMake(CGRectGetMidX(rect),0)];
[path addLineToPoint:bottomRight];
[path addQuadCurveToPoint:bottomLeftcontrolPoint:CGPointMake(CGRectGetMidX(rect), height - deltaHeight)];
[path closePath];
[path fill];}
3.添加CADisplayLink- (void)startAnimationFrom:(CGFloat)from to:(CGFloat)to {
self.from = from;
self.to = to;
self.animating = YES;
if (self.displayLink == nil) {
self.displayLink = [CADisplayLinkdisplayLinkWithTarget:selfselector:@selector(tick:)];
[self.displayLinkaddToRunLoop:[NSRunLoopcurrentRunLoop]
forMode:NSDefaultRunLoopMode];
}
}
- (void)completeAnimation {
self.animating = NO;
[self.displayLinkinvalidate];
self.displayLink = nil;
}
- (void)tick:(CADisplayLink *)displayLink {
[selfsetNeedsDisplay];}
4.調用CGFloat from = CGRectGetHeight(self.view.bounds) - CGRectGetHeight(self.blockView.bounds) / 2; CGFloat to =100; self.blockView.center = CGPointMake(self.blockView.center.x, from); [self.blockViewstartAnimationFrom:fromto:to];
[UIViewanimateWithDuration:1delay:0usingSpringWithDamping:0.85initialSpringVelocity:0options:0animations:^{
self.blockView.center = CGPointMake(self.blockView.center.x, to);
} completion:^(BOOL finished) { [self.blockViewcompleteAnimation]; }];