2013-10-14 46 views
0

我試圖將圖像添加到可以旋轉的ViewController。旋轉「MoveableImageView」對象不會旋轉到位

的問題,當我試圖旋轉可移動物體,物體移動到其初始化的地方,到原點X,Y和在那裏旋轉,而不是地方旋轉的。 我的問題是我如何防止這樣做,有沒有辦法一旦運動結束時設置對象的位置?

#import "MovableImageView.h" 

@implementation MovableImageView 

-(id)initWithImage:(UIImage *)image 
{ 
    self = [super initWithImage:image]; 
    if (self) { 
     UIRotationGestureRecognizer *rotationGestureRecognizer= [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(handleRotations:)]; 
     [self addGestureRecognizer:rotationGestureRecognizer]; 

    } 
    return self; 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesBegan:touches withEvent:event]; 
} 
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent *)event 
{ 
    [super touchesEnded:touches withEvent:event]; 

} 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesMoved:touches withEvent:event]; 
    float deltaX = [[touches anyObject] locationInView:self].x - [[touches anyObject] previousLocationInView:self].x; 
    float deltaY = [[touches anyObject] locationInView:self].y - [[touches anyObject] previousLocationInView:self].y; 
    self.transform = CGAffineTransformTranslate(self.transform, deltaX, deltaY); 
} 

-(void) handleRotations: (UIRotationGestureRecognizer *) paramSender 
{ 
    self.transform= CGAffineTransformMakeRotation(self.rotationAngleInRadians + paramSender.rotation); 
    if (paramSender.state == UIGestureRecognizerStateEnded) { 
     self.rotationAngleInRadians += paramSender.rotation; 
    } 
} 

@end 

回答

1

首先,我建議使用UIPanGestureRecognizer,而不是檢測觸摸的運動,因爲它是一個更容易處理的翻譯。當你有UIRotationGestureRecognizer,應用旋轉到現有正在重置的手勢識別器前變換:

self.transform = CGAffineTransformRotate(self.transform, paramSender.rotation; 
paramSender.rotation = 0; 

這樣你就不必跟蹤旋轉,你可以處理運動。再次,處理UIPanGestureRecognizer的時候,你可以翻譯應用到現有的變換:

-(void)pan:(UIPanGestureRecognizer*)panGesture 
{ 
    CGPoint translation = [panGesture translationInView:self]; 
    self.transform = CGAffineTransformTranslate(self.transform, translation.x, translation.y); 
    [panGesture setTranslation:CGPointZero inView:self]; 
} 

(要使用這些方法,你可能需要self.transform在初始化方法設置爲CGAffineTransformIdentity)。