检测旋转手势和缩放手势iphone sdk

时间:2010-07-12 11:53:30

标签: iphone uiimageview touch

我想旋转uiimageview还缩放图像视图,以便如何检测用户正在缩放或用户正在旋转的触摸手势?

2 个答案:

答案 0 :(得分:1)

从iOS 3.2开始,Apple引入了UIGestureRecognizer的使用。您感兴趣的两个是UIPinchGestureRecognizerUIRotationGestureRecognizer。要使用捏合手势,您可以执行以下操作:

- (void)viewDidLoad {
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    [imageView addGestureRecognizer:pinch];
    [pinch release];
}

- (void)handlePinchGesture:(UIGestureRecognizer *)sender {
    NSLog(@"New Scale: %f", sender.scale);
}

您可以为UIRotationGestureRecognizer做类似的事情。

答案 1 :(得分:0)

在viewcontroller.h文件中

记下这个属性

IBOutlet UIImageView *imgRotate;
CGFloat lastScale;
CGFloat lastRotation;

现在在你的viewcontroller.m文件中写下面的代码,

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.

UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[imgRotate addGestureRecognizer:pinchRecognizer];

UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
[rotationRecognizer setDelegate:self];
[imgRotate addGestureRecognizer:rotationRecognizer];
}

-(void)scale:(id)sender
{
if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
{
    lastScale = 1.0;
    return;
}

CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);

CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

[[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];

[imgRotate setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)sender scale];
}

-(void)rotate:(id)sender
{
if([(UIRotationGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
{
    lastRotation = 0.0;
    return;
}

CGFloat rotation = 0.0 - (lastRotation - [(UIRotationGestureRecognizer*)sender rotation]);

CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);

[[(UIRotationGestureRecognizer*)sender view] setTransform:newTransform];

[imgRotate setTransform:newTransform];
lastRotation = [(UIRotationGestureRecognizer*)sender rotation];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];

if ([touch view] == imgRotate) {
    CGPoint location = [touch locationInView:self.view];
    imgRotate.center = location;
}
}