0

我试图将图像添加到可以旋转的 ViewController。

问题是,一旦我尝试旋转可移动对象,对象就会移动到它的初始化位置,到原点 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
4

1 回答 1

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];
}

(要使用这些方法,您可能需要CGAffineTransformIdentity在初始化方法中设置 self.transform )。

于 2013-10-14T08:55:42.867 回答