核心动画——弹簧动画二

时间:2022-09-20 20:31:32

核心动画——弹簧动画一主要介绍弹簧动画的一些属性,下面介绍一下弹簧动画的另一种效果。

首先在Main.storyboard文件里面创建一个UIButton,ViewController继承于ViewController。将UIButton设置为一个属性,选中UIButton右击不放手拖到ViewController.m文件的@interface 里面并给它起名。同时,给它一个触发事件,将它拖到@implementation里面。具体操作看代码:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton
*annimationButton;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

}

- (IBAction)action:(id)sender {

UIButton
*button = sender;
button.selected
= !button.selected;
button.backgroundColor
= button.selected != YES?[UIColor colorWithRed:1.000 green:0.435 blue:0.812 alpha:1.000]:[UIColor colorWithRed:0.400 green:0.800 blue:1.000 alpha:1.000];
[self jump];
}

- (void)jump{
CASpringAnimation
*animation = [CASpringAnimation animationWithKeyPath:@"bounds"];
animation.toValue
= [NSValue valueWithCGRect:CGRectMake(0, 0, self.annimationButton.frame.size.width*1.5, self.annimationButton.frame.size.height*1.5)];
animation.mass
= 2;
animation.stiffness
= 100;
animation.damping
= 3;
animation.initialVelocity
= 30;
animation.duration
= animation.settlingDuration;
[self.annimationButton.layer addAnimation:animation forKey:
@"jump"];

}

- (void)move:(CGPoint)toPoint{

CABasicAnimation
*basicAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
basicAnimation.toValue
= [NSValue valueWithCGPoint:toPoint];
basicAnimation.duration
= 3;
basicAnimation.removedOnCompletion
= NO;
basicAnimation.fillMode
= kCAFillModeBoth;
[self.annimationButton.layer addAnimation:basicAnimation forKey:
@"move"];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

[self move:[[touches anyObject] locationInView:self.view]];
NSLog(
@"button改变位置之前的中心点x:%f y:%f",self.annimationButton.center.x,self.annimationButton.center.y);
NSLog(
@"button上面Layer的中心点x:%f y:%f",self.annimationButton.layer.position.x,self.annimationButton.layer.position.y);
//CAAnimation 只是改变图层的动画效果,并没有真实的改变视图、图层的属性值

}
@end

它的效果:

核心动画——弹簧动画二