我创建了这个代码来创建CAKeyframeAnimation,但结果并没有反弹
-(CAKeyframeAnimation *)keyframeBounceAnimationFrom:(NSValue *)from
to:(NSValue *)to
forKeypath:(NSString *)keyPath
withDuration:(CFTimeInterval)duration
{
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:keyPath];
NSMutableArray * valuesArray = [NSMutableArray array];
NSMutableArray * timeKeyArray = [NSMutableArray array];
[self createBounceFrom:from to:to Values:valuesArray keyTimes:timeKeyArray];
[animation setValues:valuesArray];
[animation setKeyTimes:timeKeyArray];
animation.duration = duration;
return animation;
}
-(void)createBounceFrom:(NSValue *)from to:(NSValue *)to Values:(NSMutableArray *)values keyTimes:(NSMutableArray *)keyTimes
{
CGPoint toPoint= [to CGPointValue];
CGFloat offset = 60;
CGFloat duration = 1.0f;
NSUInteger numberOfOscillations= 4;
[values addObject:from];
[keyTimes addObject:[NSNumber numberWithFloat:0.0f]];
//============
//ideally bouncing will depend from starting position to end poisiton as simulating real Dumping Oscillations
//============
for (NSUInteger index= 0; index <numberOfOscillations ; index++)
{
CGPoint viaPoint = CGPointMake(toPoint.x, toPoint.y + offset);
NSValue * via = [NSValue valueWithCGPoint:viaPoint];
[values addObject:via];
//add time consumed for each oscillation
[keyTimes addObject:[NSNumber numberWithFloat:duration]];
// duration = duration - 0.1;
offset = - offset ;
}
[values addObject:to];
[keyTimes addObject:[NSNumber numberWithFloat:0.6]];
}
答案 0 :(得分:3)
以下是一些很好的链接,其中包含一些如何使用它的示例:
(经过一番观察之后我发现了这个:http://www.cocoanetics.com/2012/06/lets-bounce/我觉得它反弹得更好,但更高级。所以不要把代码放在这里)
http://www.touchwonders.com/some-techniques-for-bouncing-animations-in-ios/
CAKeyframeAnimation的示例是:(取自链接)
-(void)animateGreenBall
{
NSValue * from = [NSNumber numberWithFloat:greenBall.layer.position.y];
CGFloat bounceDistance = 20.0;
CGFloat direction = (greenUp? 1 : -1);
NSValue * via = [NSNumber numberWithFloat:(greenUp ? HEIGHT_DOWN : HEIGHT_UP) + direction*bounceDistance];
NSValue * to = greenUp ? [NSNumber numberWithFloat:HEIGHT_DOWN] : [NSNumber numberWithFloat:HEIGHT_UP];
NSString * keypath = @"position.y";
[greenBall.layer addAnimation:[self keyframeBounceAnimationFrom:from via:via to:to forKeypath:keypath withDuration:.6] forKey:@"bounce"];
[greenBall.layer setValue:to forKeyPath:keypath];
greenUp = !greenUp;
}
-(CAKeyframeAnimation *)keyframeBounceAnimationFrom:(NSValue *)from
via:(NSValue *)via
to:(NSValue *)to
forKeypath:(NSString *)keyPath
withDuration:(CFTimeInterval)duration
{
CAKeyframeAnimation * animation = [CAKeyframeAnimation animationWithKeyPath:keyPath];
[animation setValues:[NSArray arrayWithObjects:from, via, to, nil]];
[animation setKeyTimes:[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:.7], [NSNumber numberWithFloat:1.0], nil]];
animation.duration = duration;
return animation;
}