前言
今天看到一个汽车爬坡的小动画,觉得挺好玩的,记录一下实现过程。
实现过程
主要代码
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor brownColor];
self.title = @"汽车爬坡";
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
[bezierPath moveToPoint:CGPointMake(20, 200)];
[bezierPath addCurveToPoint:CGPointMake(300, 200) controlPoint1:CGPointMake(100, 0) controlPoint2:CGPointMake(200, 400)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.path = bezierPath.CGPath;
pathLayer.fillColor = nil;
pathLayer.strokeColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:pathLayer];
CALayer *carLayer = [CALayer layer];
carLayer.frame = CGRectMake(0, 0, 36, 36);
carLayer.anchorPoint = CGPointMake(0.5, 0.8);
carLayer.position = CGPointMake(20, 210);
carLayer.contents = (id)[UIImage imageNamed:@"car"].CGImage;
[self.view.layer addSublayer:carLayer];
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.path = bezierPath.CGPath;
anim.duration = 4.0;
anim.rotationMode = kCAAnimationRotateAuto;
[carLayer addAnimation:anim forKey:nil];
}