iOS中的动画有两种实现方式,一种是UIView来实现动画,另一种动画是通过CALayer来实现,下面介绍两种动画的简单实现:



一、UIView动画的实现

UIView使用Context来实现动画

关键代码:

//参数1动画名称参数2要实现动画的对象上下文[UIViewbeginAnimations:@"attribute"context:_showImageView];//设置动画的时间[UIViewsetAnimationDuration:1.0f];//设置动画延迟时间//[UIViewsetAnimationDelay:2];//设置视图center实现试图移动动画_showImageView.center=CGPointMake(100,100);//设置alpha值:视图透明度_showImageView.alpha=0.2f;//设置背景颜色_showImageView.backgroundColor=[UIColorgreenColor];//UIView动画设置代理[UIViewsetAnimationDelegate:self];//动画将要开始代理方法[UIViewsetAnimationWillStartSelector:@selector(animationWillStart:context:)];//动画已经结束代理方法[UIViewsetAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];//提交动画设置,执行动画[UIViewcommitAnimations];



使用Block实现的动画:

//UIView动画,使用Block实现[UIViewanimateWithDuration:1.0fanimations:^{//通过设置translation实现视图的偏移if([self.mySwitchisOn]){//基于上一次的translation_showImageView.transform=CGAffineTransformTranslate(_showImageView.transform,50,0);}else{//基于原始的translation_showImageView.transform=CGAffineTransformMakeTranslation(-50,0);}}];



二、CALayer动画的实现

CABasic动画的实现:根据初始位置和结束位置确定动画

//CABasic有两个属性fromValue动画开始值,toValue动画结束值CABasicAnimation*animation1=[CABasicAnimationanimationWithKeyPath:@"position"];[animation1setDuration:2];animation1.fromValue=[NSValuevalueWithCGPoint:CGPointMake(150,150)];animation1.toValue=[NSValuevalueWithCGPoint:CGPointMake(200,200)];[_p_w_picpathView.layeraddAnimation:animation1forKey:@"position"];



创建一组动画:

//创建组动画对象CAAnimationGroup*group=[CAAnimationGroupanimation];//CABasic动画CABasicAnimation*animation1=[CABasicAnimationanimationWithKeyPath:@"transform.scale.y"];animation1.fromValue=@1.5;animation1.toValue=@0.5;//关键帧动画CAKeyframeAnimation*animation2=[CAKeyframeAnimationanimationWithKeyPath:@"position"];animation2.values=@[[NSValuevalueWithCGPoint:CGPointMake(100,100)],[NSValuevalueWithCGPoint:CGPointMake(200,150)],[NSValuevalueWithCGPoint:CGPointMake(100,200)],[NSValuevalueWithCGPoint:CGPointMake(200,250)]];//group添加动画数组,group中动画对象并发执行[groupsetAnimations:@[animation1,animation2]];[groupsetDuration:4.0f];[_p_w_picpathView.layeraddAnimation:groupforKey:@"group"];




完整的工程和代码见:https://github.com/winann/iOS-Animation


工程中的动画实现方法比较全,而且都有注释,大家可以直接把工程下载下来,边看边练习一下。