您的位置:首页 > 移动开发 > IOS开发

iOS 之 CABasicAnimation

2014-11-14 17:16 337 查看
CABasicAnimation 是CAPropertyAnimation的子类。该类是实现基本动画的。

基础  直接上代码
CABasicAnimation *borderAnimation = [CABasicAnimation animationWithKeyPath:@"borderColor"];//layer的属性都可以改
borderAnimation.fromValue = (id)[UIColor clearColor].CGColor;
borderAnimation.toValue = (id)[UIColor greenColor].CGColor;
borderAnimation.duration = 0.5f;
[sender.layer addAnimation:borderAnimation forKey:nil];
CABasicAnimation * borderWidth = [CABasicAnimation animationWithKeyPath:@"borderWidth"];
borderWidth.fromValue = @1;
borderWidth.toValue   = @6;
borderWidth.duration = 0.5f;
borderWidth.autoreverses = YES;
[sender.layer addAnimation:borderWidth forKey:nil];


其最主要的两个属性  fromValue /toValue 注意需要将该动画添加到CALayer层上

但是需要注意的是 在移动layer层 的位置是,只是layer层 的位置移动了,其UIView层没有发生位置变化
比如
CABasicAnimation * anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.toValue = [NSValue valueWithCGPoint:point];
anim.duration = 1.0f; //动画时间
anim.removedOnCompletion = NO;//动画完成后是否移除
anim.delegate = self;
anim.fillMode = kCAFillModeForwards;
[anim setValue:@"translationTo" forKey:@"animationType"];
[anim setValue:[NSValue valueWithCGPoint:point] forKey:@"targetPoint"];
[self.myview.layer addAnimation:anim forKey:nil];

需要设置setValue 给该动画回调方法传值, 并且 确定该动画.
解决该问题的办法是 在 动画的delegate回调方法中 重新给view.frame值
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
//其实移动的还是layer
//如果真正的想移动UIView还得移动UIViewPoint
NSString * type = [anim valueForKey:@"animationType"];
if ([type isEqualToString:@"translationTo"]) {
CGPoint point = [[anim valueForKey:@"targetPoint"] CGPointValue];
self.myview.center =point;
}
NSLog(@"%@",NSStringFromCGRect(self.myview.frame));
}

CABasicAnimation 基本动画其实可以用UIView 的动画块 去代替 
//块代码
[UIView animateWithDuration:0.25f animations:^{

} completion:^(BOOL finished) {

}];
其实这个代码块跟 上边代理方法的道理一样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息