2013-10-14 45 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)。