(一二一)核心动画基础
核心动画基于QuartzCore框架,仅仅能用于CALayer,能够实现3D效果。它在子线程中运行动画,不会堵塞主线程。
要实现核心动画,主要使用CABasicAnimation实现单步动画、使用CAKeyframeAnimation实现帧动画。
动画的主要属性有duration、keyPath、value、repeatCount等。
动画运行完成后默认会复位,要取消复位,须要下面两行代码:
anim.removedOnCompletion = NO; anim.fillMode = kCAFillModeForwards;
要实现单步动画。使用CABasicAnimation对象就可以:
利用keyPath指定操作的属性,使用toValue指定变化到的值。
CABasicAnimation *anim = [CABasicAnimation animation]; anim.duration = 0.5f; anim.keyPath = @"transform"; anim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeRotation(M_PI, 0, 1, 0)]; anim.repeatCount = 100; // 动画默认会复位。要取消复位,首先禁止动画移除。然后设置保持新位置。 anim.removedOnCompletion = NO; anim.fillMode = kCAFillModeForwards; [_blueView.layer addAnimation:anim forKey:nil];
要实现帧动画,通过CAKeyframeAnimation对象。通过多个value指定动作,或者通过贝塞尔曲线指定路径都能够:
多个value:
CAKeyframeAnimation *anim2 = [CAKeyframeAnimation animation]; anim2.duration = 0.5f; anim2.keyPath = @"position"; anim2.repeatCount = 100; NSValue *p1 = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(50, 0, 0)]; NSValue *p2 = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, 0, 0)]; NSValue *p3 = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(-50, 0, 0)]; NSValue *p4 = [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, 0, 0)]; anim2.values = @[p1,p2,p3,p4]; anim2.removedOnCompletion = NO; anim2.fillMode = kCAFillModeForwards;
路径:
CAKeyframeAnimation *anim2 = [CAKeyframeAnimation animation]; anim2.duration = 0.5f; anim2.keyPath = @"position"; anim2.repeatCount = 100; anim2.removedOnCompletion = NO; UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(100,100,200,200)]; anim2.path = path.CGPath; anim2.fillMode = kCAFillModeForwards;不要忘记把动画加入到layer。