iOS 核心动画之CAKeyFrameAnimation

本文介绍如何使用Core Animation创建关键帧动画。包括通过指定路径和值数组两种方式制作动画,并展示了如何通过触摸事件触发动画。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,给定Path,创建KeyFrame(关键帧)动画

1.1首先创建图层

    CALayer *layer = [CALayer layer];
    layer.backgroundColor = [UIColor yellowColor].CGColor;
    layer.position = CGPointMake(100, 100);
    layer.bounds = CGRectMake(0, 0, 100, 100);
    [self.view.layer addSublayer:layer];
    self.layer = layer;
1.2创建KeyFrame动画,并添加到图层上

// 按照椭圆的路径做动画
- (void)testKeyFrameAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.delegate = self;
    animation.keyPath = @"position";
    animation.duration = 2;
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddEllipseInRect(path, NULL, CGRectMake(100, 100, 200, 150));
    animation.path = path;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animation forKey:nil];
    
}
1.3通过touch方法调用,KeyFrame方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self testKeyFrameAnimation];
}

2.给定values数组,创建KeyFrame动画

2.1创建KeyFrame动画,并添加到图层上

- (void)testKeyFrameAnimation2
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.delegate = self;
    animation.keyPath = @"position";
    animation.duration = 2;
    
    NSValue *v1 = [NSValue valueWithCGPoint:CGPointMake(50, 100)];
    NSValue *v2 = [NSValue valueWithCGPoint:CGPointMake(50, 200)];
    NSValue *v3 = [NSValue valueWithCGPoint:CGPointMake(200, 200)];
    NSValue *v4 = [NSValue valueWithCGPoint:CGPointMake(200, 100)];
    NSValue *v5 = [NSValue valueWithCGPoint:CGPointMake(50, 100)];
    
    animation.values = @[v1,v2,v3,v4,v5];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    [self.layer addAnimation:animation forKey:nil];
}
2.2修改touch方法,使得touch时,调用testKeyFrameAnimation2

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self testKeyFrameAnimation2];
}


补充:CAAnimation的delegate方法,

- (void)animationDidStart:(CAAnimation *)anim
{
    NSLog(@"开始动画");
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    NSLog(@"结束动画 %d",flag);
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值