Demo地址 https://github.com/lshdfp726/GestureControlAnimation
demo 是一個(gè)利用滑動(dòng)手勢(shì)控制門開(kāi)關(guān)的動(dòng)畫(huà)!
這里貼出代碼,看起來(lái)亂的話去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;//設(shè)置為零表示禁止動(dòng)畫(huà)自動(dòng)播放
? ? [selfcreateDoorAnimation:nil];
//后臺(tái)進(jìn)入前臺(tái)的關(guān)鍵點(diǎn)重新加載一邊動(dòng)畫(huà)
? ? [[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) {
/**程序從前臺(tái)切換到后臺(tái)之后,視圖控制器上的所有視圖的layer層動(dòng)畫(huà)都被系統(tǒng)自動(dòng)remove掉了,所以監(jiān)聽(tīng)系統(tǒng)從后臺(tái)進(jìn)入前臺(tái)時(shí)在加一遍動(dòng)畫(huà),但是此時(shí)layer層其實(shí)還是上次的,有關(guān)動(dòng)畫(huà)參數(shù)的值其實(shí)沒(méi)變
就需要進(jìn)行相應(yīng)的reset重新設(shè)置 ? ,,,程序運(yùn)行時(shí)候先開(kāi)關(guān)幾次門之后,觀眾可以去掉下面這一行代碼 就可以感受結(jié)果了!
*/
? ? 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;//利用前后平移程度值差值來(lái)調(diào)整動(dòng)畫(huà)偏移時(shí)間!
NSLog(@"視圖的動(dòng)畫(huà)時(shí)間偏移量%f",timeOffset);
timeOffset =MIN(0.999,MAX(0.0, timeOffset - x));
self.doorLayer.timeOffset= timeOffset;
[reg setTranslation:CGPointZero inView:self.view];
}