UIImageView的平滑移动和捏合

时间:2010-03-25 16:00:48

标签: iphone uiimageview gesture

我有一个图像视图,我希望能够移动,并捏拉伸它。一切正常,但当我开始做任何捏动时,它有点跳跃。该位置将在两个手指之间来回跳跃。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    startLocation = [[touches anyObject] locationInView:mouth_handle];
    if([touches count] == 2) {
        NSArray *twoTouches = [touches allObjects];
        UITouch *first = [twoTouches objectAtIndex:0];
        UITouch *second = [twoTouches objectAtIndex:1];
        initialDistance = distanceBetweenPoints([first locationInView:mouth_handle],[second locationInView:mouth_handle]);
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{
    CGPoint pt = [[touches anyObject] locationInView:mouth_handle];

    CGRect frame = [mouth_handle frame];

    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;

    frame.origin.x = (frame.origin.x < 58) ? 58 : frame.origin.x;
    frame.origin.x = (frame.origin.x > (260 - mouth_handle.frame.size.width)) ? (260 - mouth_handle.frame.size.width) : frame.origin.x;
    frame.origin.y = (frame.origin.y < 300) ? 300 : frame.origin.y;
    frame.origin.y = (frame.origin.y > 377) ? 377 : frame.origin.y;

    if(frame.origin.x - prevDistanceX > 2 && frame.origin.x - prevDistanceX < -2)
        frame.origin.x = prevDistanceX;
    if(frame.origin.y - prevDistanceY > 2 && frame.origin.y - prevDistanceY < -2)
        frame.origin.y = prevDistanceY;

    prevDistanceX = frame.origin.x;
    prevDistanceY = frame.origin.y;

    CGFloat handleWidth = mouth_handle.frame.size.width;

    if([touches count] == 2) {
        NSArray *twoTouches = [touches allObjects];
        UITouch *first = [twoTouches objectAtIndex:0];
        UITouch *second = [twoTouches objectAtIndex:1];
        CGFloat currentDistance = distanceBetweenPoints([first locationInView:mouth_handle],[second locationInView:mouth_handle]);

        handleWidth = mouth_handle.frame.size.width + (currentDistance - initialDistance);
        handleWidth = (handleWidth < 60) ? 60 : handleWidth;
        handleWidth = (handleWidth > 150) ? 150 : handleWidth;
        if(initialDistance == 0) {
            initialDistance = currentDistance;
        }

        initialDistance = currentDistance;
    }

    mouth_handle.frame = CGRectMake(frame.origin.x, frame.origin.y, handleWidth, 15);
}

有关如何使这更顺畅的想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用UIScrollview执行此操作;它是直接内置的。

答案 1 :(得分:0)

通过手指之间的跳跃,你的意思是你无法区分第一个和第二个手指吗?

我要做的是计算手指之间的角度。按角度我的意思是,如果你画一个圆圈,一个触摸作为中心,另一个圆圈,你可以确定第一个触摸正上方的点和第二个触摸之间的角度。 如果两个事件之间的角度差大于.5Pi(1/4圈),您可以假设触摸已切换,您可以纠正。

我希望你理解我的意思。