使用UITouch时如何获得触摸偏移

时间:2012-08-16 03:58:16

标签: objective-c ios cocoa-touch uigesturerecognizer uitouch

使用UITouch时如何获得触摸偏移?我正在做一个像遥控器这样的项目。我有一个多点触摸的视图,我希望视图像Mac的触摸板一样,所以当人们移动控制鼠标时我需要触摸偏移。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这可以通过测量从屏幕中心到当前触摸位置的对角线距离UIPanGestureRecognizer来实现。

#import <QuartzCore/QuartzCore.h>

声明手势并将其挂钩到self.view,以便整个屏幕响应触摸事件。

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(myPanRecognizerMethod:)];
[pan setDelegate:self];
[pan setMaximumNumberOfTouches:2];
[pan setMinimumNumberOfTouches:1];
[self.view setUserInteractionEnabled:YES];
[self.view addGestureRecognizer:pan];

然后在这个方法中,我们使用手势识别器状态:UIGestureRecognizerStateChanged更新和整数,当触摸位置改变时,测量触摸位置和屏幕中心之间的对角线距离。

-(void)myPanRecognizerMethod:(id)sender
{
    [[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];
    if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateChanged) {
        CGPoint touchLocation = [sender locationOfTouch:0 inView:self.view];
        NSNumber *distanceToTouchLocation = @(sqrtf(fabsf(powf(self.view.center.x - touchLocation.x, 2) + powf(self.view.center.y - touchLocation.y, 2))));
        NSLog(@"Distance from center screen to touch location is == %@",distanceToTouchLocation);
    }
}