1

我正在移植一个现有的 iOS 应用程序来学习 C4,我需要使用自定义动画来使用 CAKeyframeAnimation 从屏幕外滑入具有“弹入”效果的图像。

对我来说,使用 C4 实现更复杂的动画的最佳方法是什么?

图像创建

C4Image *v = [C4Image imageNamed:@"assets/images/ca/defense.png"];
v.frame = CGRectMake(1500, 300, 400, 400); // off screen
[self addImage:v];

先前实现中使用的 CAKeyframeAnimation

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position.x"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.duration = 0.5;

int steps = 100;
NSMutableArray *values = [NSMutableArray arrayWithCapacity:steps];
double value = 0;
float e = 2.71;
for (int t = 0; t < steps; t++) {
    value = 200 * pow(e, -0.055*t) * cos(0.08*t) + x; //418
    [values addObject:[NSNumber numberWithFloat:value]];
}

animation.values = values;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.delegate = self;
animation.beginTime = CACurrentMediaTime() + delay;
4

1 回答 1

0

C4 中的所有可视对象都有一个您可以访问的图层属性。创建 a 时,CAKeyframeAnimation 您可以将此属性用作要添加动画的对象。

上面的代码工作得很好(尽管我确实稍微调整了数字以确保对象在画布上)。

我将代码更改为:

#import "C4WorkSpace.h"

@implementation C4WorkSpace {
    C4Image *v;
}

-(void)setup {
    v = [C4Image imageNamed:@"C4Table"];
    v.origin = CGPointMake(self.canvas.center.x , self.canvas.center.y);
    v.borderColor = C4RED;
    v.borderWidth = 1.0f;
    v.width = self.canvas.width / 2.0f;
    [self.canvas addImage:v];
}

-(void)touchesBegan {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation
                                      animationWithKeyPath:@"position.x"];
    animation.timingFunction = [CAMediaTimingFunction
                                functionWithName:kCAMediaTimingFunctionLinear];
    animation.duration = 0.5;

    int steps = 100;
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:steps];
    double value = 0;
    float e = 2.71f;
    float x = v.origin.x;
    for (int t = 0; t < steps; t++) {
        value = 200 * pow(e, -0.025*t) * cos(0.08*t) - x; //418
        [values addObject:@(value)];
    }

    animation.values = values;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.delegate = self;
    animation.beginTime = CACurrentMediaTime() + 1.0f;

    [v.layer addAnimation:animation forKey:@"position.x"];
}

@end

你可以抓住这个工作git repo

我必须做的主要事情是:

[v.layer addAnimation:animation forKey:@"position.x"];

我所做的其余更改只是坐标和颜色,以确保一切正常。

于 2013-04-26T14:31:50.370 回答