弹性动画~~~~ EasingFunction

来源:互联网 发布:卫星免费网络电视直播 编辑:程序博客网 时间:2024/06/05 11:00

#import <QuartzCore/QuartzCore.h>

#import <objc/runtime.h>


#define kAnimationDelay 0.08

typedef CGFloat (^EasingFunction)(CGFloat,CGFloat, CGFloat, CGFloat);


static EasingFunction easeOutElastic = ^CGFloat(CGFloat t,CGFloat b, CGFloat c, CGFloat d) {

    CGFloat amplitude = 5;

    CGFloat period = 0.6;

    CGFloat s = 0;

    if (t == 0) {

        return b;

    }

    else if ((t /= d) ==1) {

        return b + c;

    }

    

    if (!period) {

        period = d * .3;

    }

    

    if (amplitude < abs(c)) {

        amplitude = c;

        s = period / 4;

    }

    else {

        s = period / (2 * M_PI) * sin(c / amplitude);

    }

    

    return (amplitude * pow(2, -10 * t) *sin((t * d - s) * (2 * M_PI) / period) + c + b);

};


调用方法


- (void)animateLayer:(CALayer *)layer

         withKeyPath:(NSString *)keyPath

                  to:(CGFloat)endValue {

    CGFloat startValue = [[layer valueForKeyPath:keyPath] floatValue];

    

    CAKeyframeAnimation *animation = [CAKeyframeAnimationanimationWithKeyPath:keyPath];

    animation.timingFunction = [CAMediaTimingFunctionfunctionWithName:kCAMediaTimingFunctionLinear];

    animation.fillMode = kCAFillModeForwards;

    animation.removedOnCompletion =NO;

    animation.duration = self.animationDuration;

    

    CGFloat steps = 100;

    NSMutableArray *values = [NSMutableArrayarrayWithCapacity:steps];

    CGFloat delta = endValue - startValue;

    EasingFunction function =easeOutElastic;

    

    for (CGFloat t =0; t < steps; t++) {

        [values addObject:@(function(animation.duration * (t / steps), startValue, delta, animation.duration))];

    }

    

    animation.values = values;

    [layer addAnimation:animation forKey:nil];

}

- (void)open {

    _isOpen = YES;

    

    for (UIView *itemin self.items) {

        [selfperformSelector:@selector(showItem:)withObject:item afterDelay:kAnimationDelay * [self.itemsindexOfObject:item]];

    }

}




- (void)showItem:(UIView *)item {

   [NSObject cancelPreviousPerformRequestsWithTarget:item.layer];

    item.layer.opacity =1.0f;

    

    CGPoint position = item.layer.position;

    

    if (self.menuIsVertical) {

        position.x +=self.menuPosition ==HMSideMenuPositionRight ? - self.menuWidth :self.menuWidth;

        

        [self animateLayer:item.layer

               withKeyPath:@"position.x"

                        to:position.x];

    } else {

        position.y +=self.menuPosition ==HMSideMenuPositionTop ? self.menuHeight : -self.menuHeight;


        [self animateLayer:item.layer

               withKeyPath:@"position.y"

                        to:position.y];

    }

    

    item.layer.position = position;

}


原创粉丝点击