2012-01-08 45 views
8

我的手勢識別器存在一個小問題。基於旋轉的泛姿勢會擾亂方向

我有一個叫做「Sprite」的類,它只是一個UIImageView。 Sprite擁有自己的手勢識別器和處理方法,以便用戶可以平移,旋轉和調整圖形大小。

這裏是我的代碼:

-(void)setup{ //sets up the imageview... 
//add the image, frame, etc. 
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)]; 
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; 
    UIRotationGestureRecognizer *rotateGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)]; 

    [self addGestureRecognizer:panGesture]; 
    [self addGestureRecognizer:pinchGesture]; 
    [self addGestureRecognizer:rotateGesture]; 
} 

//handling methods 
-(void)handlePinch:(UIPinchGestureRecognizer *)recognizer{ 
    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale); 
    recognizer.scale = 1; 
} 

-(void)handleRotate:(UIRotationGestureRecognizer *)recognizer{ 
    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation); 
    recognizer.rotation = 0; 
} 
-(void)handlePan:(UIPanGestureRecognizer *)recognizer{ 
    CGPoint translation = [recognizer translationInView:self]; 
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y); 
    [recognizer setTranslation:CGPointMake(0, 0) inView:self] 
} 

所以基本上每個人的正常工作自己。但是,當我旋轉或調整imageView的大小時,平移會變得有問題。例如,如果您顛倒旋轉imageView,則平移手勢將以相反方向移動圖像(向上向下,向左拖動向右移動等)。同樣,調整大小的精靈不會像以前那樣以相同的速度/距離平移。

關於如何解決這個問題的任何想法?我寧願將此代碼保留在Sprite類中,而不是ViewController(如果可能)。謝謝。

回答

12

而不是translationInView:self,請嘗試translationInView:self.superview。

+0

Tx @Jerry,很好的答案。這讓我完全瘋了! – 2012-08-07 01:38:30

+0

@Jerry,它很好用... – 2012-09-05 11:06:26