[动画学习]containsPoint:和hitTest:
CALayer并不关心任何响应链事件,所以不能直接处理触摸事件或者手势。但是它有一系列的方法帮你处理事件:-containsPoint:和-hitTest:
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *layerView;
@property (nonatomic,strong) CALayer *buleLayer;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor brownColor];
//点击方法测试
self.buleLayer = [CALayer layer];
self.buleLayer.frame = CGRectMake(50.0f, 50.0f, 100.0f, 100.0f);
self.buleLayer.backgroundColor = [UIColor blueColor].CGColor;
//add it to our view
[self.layerView.layer addSublayer:self.buleLayer];
}
点击时间效果图
-containsPoint:-hitTest:-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint point = [[touches anyObject]locationInView:self.view];
// 方法containsPoint:判断点是否在layer 返回值为bool
point = [self.layerView.layer convertPoint:point fromLayer:self.view.layer];
if ([self.layerView.layer containsPoint:point]) {
point = [self.buleLayer convertPoint:point fromLayer:self.layerView.layer];
if ([self.buleLayer containsPoint:point]) {
[[[UIAlertView alloc]initWithTitle:@"在蓝的里面" message:nil delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil] show];
}else{
[[[UIAlertView alloc] initWithTitle:@"在白的里面"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint point = [[touches anyObject]locationInView:self.view];
//方法hitTest:判断点是否在layer返回值为layer
CALayer *layer = [self.layerView.layer hitTest:point];
if (layer == self.buleLayer) {
[[[UIAlertView alloc]initWithTitle:@"在蓝的里面" message:nil delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil] show];
}else{
[[[UIAlertView alloc] initWithTitle:@"不在蓝的里面"
message:nil
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] show];
}
}
注意当调用图层的-hitTest:方法时,测算的顺序严格依赖于图层树当中的图层顺序(和UIView处理事件类似)
zPosition属性可以明显改变屏幕上图层的顺序,但不能改变事件传递的顺序。这意味着如果改变了图层的z轴顺序,你会发现将不能够检测到最前方的视图点击事件,这是因为被另一个图层遮盖住了,虽然它的zPosition值较小,但是在图层树中的顺序靠前。
-end