标签:ios动画 移动动画 coreanimation cakeyframeanimation cabasicanimation
对Core Animation来说,不管是显式动画还是隐式动画,对其设置frame都是立即设置的,比如说给一个UIView做移动动画,虽然看起来frame在持续改变,但其时它的frame已经是最终值了,这种情况下,哪怕这个UIView是UIButton的实例,其触发touch事件的范围还是最终frame的地方。比如一个Button的frame是(0,0,100,100),要把它从0,0移动到200,200,在这种情况下:CGSize layerSize = CGSizeMake(100, 100); CALayer *movingLayer = [CALayer layer]; movingLayer.bounds = CGRectMake(0, 0, layerSize.width, layerSize.height); [movingLayer setBackgroundColor:[UIColor orangeColor].CGColor]; movingLayer.anchorPoint = CGPointMake(0, 0); [self.view.layer addSublayer:movingLayer]; self.movingLayer = movingLayer;这里面只有anchorPoint重要一些,因为anchorPoint能影响position的取值,对Layer来说,frame是抽象的,只有bounds和position是真实存在的,并且设置frame和设置anchorPoint的顺序不同,开始看到的结果也不同:
CAKeyframeAnimation *moveLayerAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; //moveLayerAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)]; //moveLayerAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(320 - self.movingLayer.bounds.size.width, 0)]; moveLayerAnimation.values = @[[NSValue valueWithCGPoint:CGPointMake(0, 0)], [NSValue valueWithCGPoint:CGPointMake(320 - self.movingLayer.bounds.size.width, 0)]]; moveLayerAnimation.duration = 2.0; moveLayerAnimation.autoreverses = YES; moveLayerAnimation.repeatCount = INFINITY; moveLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [self.movingLayer addAnimation:moveLayerAnimation forKey:@"move"];如果是用CABasicAnimation做动画,则用fromValue及toValue替换setValues,timingFunction直接用线性,不用做其他变换,关于这个属性的预置值,我在另一篇博文中有提到。
........ self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)]; [self.view addGestureRecognizer:self.tapGesture]; } -(void)click:(UITapGestureRecognizer *)tapGesture { CGPoint touchPoint = [tapGesture locationInView:self.view]; if ([self.movingLayer.presentationLayer hitTest:touchPoint]) { NSLog(@"presentationLayer"); } }我在最开始的时候有提到,动画的过程只是看起来是动态变换的,其内部的值已经是固定的了,在这种情况下,Layer内部会通过复制一个当前Layer的副本来展示动画过程,而我们可以通过访问Layer的presentationLayer属性来得到这个副本的副本,通过presentationLayer我们可以知道当前动画已经进行到了屏幕的哪个位置上了,再直接通过hitTest来判定是不是一次有效点击即可。
iOS 为移动动画中的View添加touch事件,布布扣,bubuko.com
标签:ios动画 移动动画 coreanimation cakeyframeanimation cabasicanimation
原文地址:http://blog.csdn.net/zhangao0086/article/details/38356691