Demo地址 https://github.com/lshdfp726/GestureControlAnimation
demo 是一个利用滑动手势控制门开关的动画!
这里贴出代码,看起来乱的话去git clone,代码不多
@interfaceViewController()
@property(weak,nonatomic)IBOutlet UIImageView*doorImageView;
@property(nonatomic,strong) CALayer *doorLayer;
@property(weak,nonatomic)IBOutlet UIView *containerView;
@end
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.doorLayer= [CALayerlayer];
self.doorLayer.frame=self.containerView.bounds;
self.doorLayer.position=CGPointMake(self.doorLayer.position.x-256/4,self.doorLayer.position.y);
self.doorLayer.anchorPoint=CGPointMake(0,0.5);
self.doorLayer.contents= (__bridgeid)[UIImageimageNamed:@"door.jpeg"].CGImage;
[self.containerView.layeraddSublayer:self.doorLayer];
CATransform3Dperspective =CATransform3DIdentity;
perspective.m34= -1.0/500.0;
self.containerView.layer.sublayerTransform= perspective;
UIPanGestureRecognizer*pan = [[UIPanGestureRecognizeralloc]init];
[panaddTarget:selfaction:@selector(panGestureRecognizer:)];
[self.viewaddGestureRecognizer:pan];
self.doorLayer.speed=0.0;//设置为零表示禁止动画自动播放
[selfcreateDoorAnimation:nil];
//后台进入前台的关键点重新加载一边动画
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createDoorAnimation:) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void)createDoorAnimation:(NSNotification*)noti {
CABasicAnimation*animation = [CABasicAnimationanimation];
animation.keyPath=@"transform.rotation.y";
animation.toValue=@(-M_PI_2);
animation.duration=1.0;
[self.doorLayeraddAnimation:animationforKey:nil];
if(noti) {
/**程序从前台切换到后台之后,视图控制器上的所有视图的layer层动画都被系统自动remove掉了,所以监听系统从后台进入前台时在加一遍动画,但是此时layer层其实还是上次的,有关动画参数的值其实没变
就需要进行相应的reset重新设置 ,,,程序运行时候先开关几次门之后,观众可以去掉下面这一行代码 就可以感受结果了!
*/
self.doorLayer.timeOffset=0.0;
}
}
- (void)panGestureRecognizer:(UIPanGestureRecognizer*)reg {
CGFloatx = [reg translationInView:self.view].x;//理解为获取手指平移的程度(拖拽的力度)
x /=200.0f;
NSLog(@"translationInView==%f",x);
CFTimeInterval timeOffset =self.doorLayer.timeOffset;//利用前后平移程度值差值来调整动画偏移时间!
NSLog(@"视图的动画时间偏移量%f",timeOffset);
timeOffset =MIN(0.999,MAX(0.0, timeOffset - x));
self.doorLayer.timeOffset= timeOffset;
[reg setTranslation:CGPointZero inView:self.view];
}