簡體   English   中英

平滑移動和捏住UIImageView

[英]Smooth move and pinch of UIImageView

我有一個圖像視圖,希望能夠四處移動並捏住以拉伸它。 一切正常,但是當我開始做捏動作時有點跳動。 該位置將在兩個手指之間來回跳躍。

- (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);
}

關於如何使它更平滑有什么想法?

您可以使用UIScrollview進行此操作; 它直接內置在其中。

通過在手指之間跳躍,您是說無法區分第一根和第二根手指嗎?

我要做的是計算手指之間的角度。 角度是指如果您以一個觸摸為中心繪制一個圓,另一個在圓的邊緣繪制一個圓,則可以確定第一次觸摸上方的點與第二次觸摸之間的角度。 如果兩個事件之間的角度差大於0.5Pi(1/4圈),則可以假定觸摸已切換,可以對此進行校正。

我希望你明白我的意思。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM