如何通过手势捕获CALayer

排列和拖动视图知道如何通过手势捕获视图,在如何通过手势选择到子视图知道如何捕获视图的子视图。现在有个问题,如何通过手势捕获视图内部的层(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 <UIKit/UIKit.h> 
#import <QuartzCore/QuartzCore.h>

#define RADIAS 180

@interface AnimationView : UIView <UIGestureRecognizerDelegate>{
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]];







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值