iOS中的基本动画
iOS的动画需要导入#import <QuartzCore/QuartzCore.h>框架
通过点击屏幕触发动画
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
UITouch *touch = touches.anyObject; // 拿到触摸对象
CGPoint location = [touch locationInView:]; //获取触摸点在哪个视图
//平移动画到指定点
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
[anim setToValue:[NSValue valueWithCGPoint:point]];//不设置fromValue 因为默认就是当前value
// 2) 动画的时长
[anim setDuration:1.0f];
[anim setDelegate:self]; //监听动画的开始和结束
[anim setRemovedOnCompletion:NO]; //设置视图保持动画后的状态
// forwards是逐渐逼近目标点
[anim setFillMode:kCAFillModeForwards];
//设置要修改的位置
[anim setValue:[NSValue valueWithCGPoint:point] forKey:@"targetPoint"];
[anim setValue:@"translationTo" forKey:@"animationType"];
// 将动画添加到图层之后,系统会按照定义好的属性开始动画,通常程序员不在与动画进行交互
[self.myView.layer addAnimation:anim forKey:nil];
//动画结束的时候最相应的动作
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
NSString *type = [anim valueForKey:@"animationType"];
if ([type isEqualToString:@"translationTo"]) {
// 1. 通过键值取出需要移动到的目标点
CGPoint point = [[anim valueForKey:@"targetPoint"]CGPointValue];
NSLog(@"目标点: %@", NSStringFromCGPoint(point));
// 2. 设置myView的坐标点
[self.myView setCenter:point];
}
}