我试图将图像添加到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
答案 0 :(得分: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
。