在排列和拖动视图知道如何通过手势捕获视图,在如何通过手势选择到子视图知道如何捕获视图的子视图。现在有个问题,如何通过手势捕获视图内部的层(Layer),如果能,怎么捕获。
捕获到Layer是很重要的,这样才能针对具体的Layer做操作,比如拖动,比如反转等。
答案是肯定的,下面写个例子说明一下。
示例中的图,是在视图默认Layer下的子Layer。当touch(手指拖动)该Layer以外的部分,则只打印pan …,当在该Layer上拖动时,除了打印pan..以外,还会打印catch it!
这里需要用到CALayer的hitTest方法。
控制器代码很简单。
头文件:
@interface TestGestureViewController : UIViewController{
AnimationView *animationView;
实现文件中:
- (void)viewDidLoad {
[super viewDidLoad];
animationView=[[AnimationView alloc] initWithFrame:CGRectMake(0, 0, 768, 1024)];
animationView.backgroundColor=[UIColor blueColor];
[self.view addSubview:animationView];
视图部分,头文件:
#import
#import
#define RADIAS 180
@interface AnimationView : UIView
CALayer *startLayer;
}
- (void) initLayers;
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer;
@end
实现文件:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initLayers];
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
[panGesture setMaximumNumberOfTouches:2];
[self addGestureRecognizer:panGesture];
[panGesture release];
}
return self;
}
- (void) initLayers{
startLayer=[CALayer layer];
UIImage *image=[UIImage imageNamed:@"4.png"];
startLayer.bounds=CGRectMake(0, 0, image.size.width, image.size.height);
startLayer.contents=(id)[image CGImage];
startLayer.position=CGPointMake(768/2-RADIAS, 1024/2);
[self.layer addSublayer:startLayer];
[image release];
}
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer{
NSLog(@"pan …");
CALayer *layer=[self.layer hitTest:[gestureRecognizer locationInView:self]];
if (layer==startLayer) {
NSLog(@"catch it!");
}
}
其中,捕获Layer的代码:
CALayer *layer=[self.layer hitTest:[gestureRecognizer locationInView:self]];