这个区别很重要,你只用记住,如果是用UIView做动画,设置的frame是有效的; 如果CALaye做动画设置的frame是无效的,你应该在动画结束后显式地指定position的值 |
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"); } }我在最开始的时候有提到,动画的过程只是看起来是动态变换的,其内部的值已经是固定的了。