iOS学习笔记33

一,核心动画

-(UIColor *)createColor{

    CGFloat r = arc4random_uniform(255)/255.0;

    CGFloat g = arc4random_uniform(255)/255.0;

    CGFloat b = arc4random_uniform(255)/255.0;

    CGFloat ap = arc4random_uniform(255)/255.0;

    UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:ap];

    return color;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    

    self.layer = [CALayer layer];

    self.layer.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor;

    

    self.layer.position = CGPointMake(100, 100);

    self.layer.bounds = CGRectMake(0, 0, 100, 100);

    self.layer.contents = (id)[UIImage imageNamed:@"1"].CGImage;

    

    [self.view.layer addSublayer:self.layer];

    

    // Do any additional setup after loading the view, typically from a nib.

}

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

{

    

   

    [CATransaction begin];

    [CATransaction setAnimationDuration:2.0];

    

//    if (CGRectContainsPoint(self.layer.frame, point)) {

    UITouch *touch = [touches anyObject];

    CGPoint point = [touch locationInView:self.view];

    self.layer.position = point;//    }

    self.layer.backgroundColor = [self createColor].CGColor;

    

    CGFloat width = arc4random()%100 + 10;

    self.layer.frame = CGRectMake(0, 0, width, width);

    [CATransaction commit];

}

二,基础动画

  CGPoint tapPoint = [tap locationInView:self.view];

    

    //创建基本动画

    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"position"];

    //设置动画的属性

    [basicAnimation setDuration:2.0];

    CGPoint point = self.layer.position;

    /**

     *封装point

     **/

    NSValue *value1 = [NSValue valueWithCGPoint:point];

    NSValue *value2 = [NSValue valueWithCGPoint:tapPoint];

    basicAnimation.fromValue = value1;//动画的开始点

    basicAnimation.toValue =  value2;

    //将动画添加到相应的层里面

    [self.layer addAnimation:basicAnimation forKey:@"position"];

效果如图:

有一个问题,这个动画动完之后就回到初始位置,这一点区别于核心动画

//核心动画修改了层的属性

//基础动画 没有修改层的属性

方法是修改 属性 

    basicAnimation.removedOnCompletion = NO;

    basicAnimation.fillMode = kCAFillModeForward;//动画结束后保持的最后状态

但是,这种方法如果再点击,还是会回到原来的起点变动

所以需要修改属性

原文地址:https://www.cnblogs.com/adodo/p/5241516.html