CALayer+PKDownloadButtonAnimations.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //
  2. // CALayer+PKDownloadButtonAnimations.m
  3. // Download
  4. //
  5. // Created by Pavel on 31/05/15.
  6. // Copyright (c) 2015 Katunin. All rights reserved.
  7. //
  8. #import "CALayer+PKDownloadButtonAnimations.h"
  9. static NSString *kRorationEndKey = @"PKLayerRorationEndKey";
  10. @implementation CALayer (PKDownloadButtonAnimations)
  11. - (void)addRotationAnimationWithKey:(NSString *)animationKey fullRotationDuration:(NSTimeInterval)fullRotationDuration {
  12. NSNumber *fromValue = [self.presentationLayer valueForKeyPath:@"transform.rotation"];
  13. [self removeAnimationForKey:kRorationEndKey];
  14. CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
  15. rotationAnimation.fromValue = fromValue;
  16. rotationAnimation.toValue = @([rotationAnimation.fromValue floatValue] + (2. * M_PI));
  17. rotationAnimation.duration = fullRotationDuration;
  18. rotationAnimation.repeatCount = HUGE_VALF;
  19. rotationAnimation.removedOnCompletion = NO;
  20. [self addAnimation:rotationAnimation forKey:animationKey];
  21. }
  22. - (void)removeRotationAnimationWithKey:(NSString *)animationKey {
  23. [self removeRotationAnimationWithKey:animationKey fullRotationDuration:0.0];
  24. }
  25. - (void)removeRotationAnimationWithKey:(NSString *)animationKey fullRotationDuration:(NSTimeInterval)fullRotationDuration {
  26. NSNumber *fromValue = [self.presentationLayer valueForKeyPath:@"transform.rotation"];
  27. NSNumber *toValue = @((fromValue.doubleValue < 0.0) ? 0.0 : 2.0 * M_PI);
  28. [self removeAnimationForKey:animationKey];
  29. const NSTimeInterval animationDuration = ABS(toValue.doubleValue - fromValue.doubleValue) * (fullRotationDuration / (2.0 * M_PI));
  30. if (fromValue.doubleValue != 0.0 && ![fromValue isEqualToNumber:toValue] && animationDuration > 0.0) {
  31. [CATransaction begin];
  32. CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
  33. rotationAnimation.fromValue = fromValue;
  34. rotationAnimation.toValue = toValue;
  35. rotationAnimation.duration = animationDuration;
  36. [CATransaction setCompletionBlock:^{
  37. [self removeAnimationForKey:kRorationEndKey];
  38. }];
  39. [self addAnimation:rotationAnimation forKey:kRorationEndKey];
  40. [CATransaction commit];
  41. }
  42. else {
  43. [self removeAnimationForKey:kRorationEndKey];
  44. }
  45. }
  46. @end