在如何通过手势捕获CALayer基础上做了个示例,两个CALayer的联动,当拖动左侧的Layer的时候,右侧的Layer随动。因为右侧的动画没有关闭,有延迟,产生随动的效果。如果不想延迟,可参考拖动动画的问题及解决。
在视图的头文件:
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>#define RADIAS 180
@interface AnimationView : UIView <UIGestureRecognizerDelegate>{
CALayer *startLayer;
CALayer *startLayer2;
}- (void) initLayers;
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer;
@end
实现文件:
#import "AnimationView.h"
@implementation AnimationView
- (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];
startLayer2=[CALayer layer];
image=[UIImage imageNamed:@"5.png"];
startLayer2.bounds=CGRectMake(0, 0, image.size.width, image.size.height);
startLayer2.contents=(id)[image CGImage];
startLayer2.position=CGPointMake(768/2+RADIAS, 1024/2);
[self.layer addSublayer:startLayer2];
[image release];
}- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer{
NSLog(@"pan …");
CGPoint locationInView = [gestureRecognizer locationInView:self];
CALayer *layer=[self.layer hitTest:locationInView];
if (layer==startLayer) {
NSLog(@"catch it!");
[CATransaction begin];
CGPoint newLocation=locationInView;
newLocation.x+=RADIAS*2;
startLayer2.position=newLocation;
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithBool:YES]
forKey:kCATransactionDisableActions];
startLayer.position=locationInView;
[CATransaction commit];
[CATransaction commit];
}
}