核心动画图像序列

4

如何使用核心动画创建图像序列。我想要:

添加图像1并持续1秒,然后移除图像。

添加图像2并持续2秒,然后移除图像。

添加图像1并持续3秒,然后移除图像。

    CGImageRef image1 = [self getImage1];
    CALayer *image1Layer = [CALayer layer];
    image1Layer.bounds = CGRectMake(0, 0, 480, 320);
    image1Layer.position = CGPointMake(0, 0);
    image1Layer.contents = (id)image1;


    CABasicAnimation *animation1 = [CABasicAnimation animationWithKeyPath:@"animation"];
    animation1.repeatCount = 0; 
    animation1.duration = 2.0;
    animation1.removedOnCompletion = YES; // i would like to remove image here
    animation1.beginTime = AVCoreAnimationBeginTimeAtZero; 
    [image1Layer addAnimation:animation1 forKey:nil];

以上代码添加了一张图片,但没有删除它。
谢谢。
2个回答

10

最简单的方法是使用CABasicAnimation来设置内容的关键字:

CABasicAnimation *animation = [CABasicAnimation animation];
animation.fromValue = (id)[UIImage imageNamed:@"image1.png"].CGImage;
animation.toValue = (id)[UIImage imageNamed:@"image2.png"].CGImage;
animation.duration = 1.0f;
animation.repeatCount = HUGE_VAL;
//  animation.autoreverses = YES;
[image1Layer addAnimation:animation forKey:@"contents"];

这个动画将无限地在图像1和图像2之间更改层内容。您可能希望为了更平滑的过渡设置autoreverses属性 - 以任何方式测试动画,选择您最喜欢的选项。


我遇到了一个错误:在参数传递中无法将'CGImage*'转换为'objc_object*'。我想添加大约十张图片,并从一张图片直接切换到另一张图片。感谢您的回答。 - user346443
1
抱歉,您需要将CGImage显式转换为ID - 这应该可以解决错误。要通过10个图像进行动画处理,您可以使用类似于CABasicAnimation的CAKeyFrameAnimation方式,只需要提供一个图像数组来迭代和一个keyTimes数组来控制动画时间。 - Vladimir
@Vladimir- 我在你的代码中如何播放一个图像数组的序列,就像这个问题所示:https://dev59.com/jnfZa4cB1Zd3GeqPOCZ1... 我遇到了同样的问题。 - Vivek Sehrawat
@VivekSehrawat,你需要找出一种方法,可以不将所有100张图片加载到内存中。我的解决方案无法直接适用于此。 - Vladimir
@Vladimir- 谢谢,但你能详细解释一下Brad Lanson在http://stackoverflow.com/questions/442076/method-for-animating-images-like-a-movie-on-iphone-without-using-mpmovieplayer的答案吗? - Vivek Sehrawat
一个可以处理多张图片而不会导致系统内存崩溃的工作解决方案在这里:https://stackoverflow.com/questions/442076/method-for-animating-images-like-a-movie-on-iphone-without-using-mpmovieplayer#answer-6077394 - MoDJ

0

你也可以使用CAKeyframeAnimation来实现这个效果。按照以下步骤进行:

  1. 创建一个UIImage数组,并添加图片
  2. 准备CAKeyframeAnimation动画
  3. 准备CALayer
  4. 将动画添加到图层中

参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接