使用CADisplayLink实现果冻效果动画(学习于Glow 技术团队)

来源:互联网 发布:软件项目管理培训 编辑:程序博客网 时间:2024/05/01 23:15

使用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];
    }];
1 0
原创粉丝点击