簡體   English   中英

向 UIPanGestureRecognizer 添加慣性

[英]adding inertia to a UIPanGestureRecognizer

我正在嘗試在有效的屏幕上移動子視圖,但我也想為對象添加慣性或動量。
我已經擁有的 UIPanGestureRecognizer 代碼如下。

提前致謝。

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self       action:@selector(handlePan:)];
[self addGestureRecognizer:panGesture];

(void)handlePan:(UIPanGestureRecognizer *)recognizer
{

    CGPoint translation = [recognizer translationInView:self.superview];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                     recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.superview];

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        [self.delegate card:self.tag movedTo:self.frame.origin];
    }
}

再次感謝。

看看RotationWheelAndDecelerationBehaviour 有一個示例說明如何對線性平移和旋轉運動進行減速。 訣竅是查看當用戶結束觸摸並以小減速繼續在該方向上時的速度是多少。

好吧,我不是專業人士,但是,檢查多個答案后,我設法制作了自己滿意的代碼。

請告訴我如何改進它,以及我是否使用過任何不好的做法。

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

CGPoint translatedPoint = [recognizer translationInView:self.postViewContainer];
CGPoint velocity = [recognizer velocityInView:recognizer.view];

float bottomMargin = self.view.frame.size.height - containerViewHeight;
float topMargin = self.view.frame.size.height - scrollViewHeight;

if ([recognizer state] == UIGestureRecognizerStateChanged) {

    newYOrigin = self.postViewContainer.frame.origin.y + translatedPoint.y;

    if (newYOrigin <= bottomMargin  && newYOrigin >= topMargin) {
        self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + translatedPoint.y);
    }
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.postViewContainer];
}

if ([recognizer state] == UIGestureRecognizerStateEnded) {

    __block float newYAnimatedOrigin = self.postViewContainer.frame.origin.y + (velocity.y / 2.5);

    if (newYAnimatedOrigin <= bottomMargin && newYAnimatedOrigin >= topMargin) {
        [UIView animateWithDuration:1.2 delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^ {
                             self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + (velocity.y / 2.5));
                         }
                         completion:^(BOOL finished) {
                             [self.postViewContainer setFrame:CGRectMake(0, newYAnimatedOrigin, self.view.frame.size.width, self.view.frame.size.height - newYAnimatedOrigin)];
                         }
         ];
    }
    else {
        [UIView animateWithDuration:0.6 delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^ {
                             if (newYAnimatedOrigin > bottomMargin) {
                                 self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, bottomMargin + self.postViewContainer.frame.size.height / 2);
                             }

                             if (newYAnimatedOrigin < topMargin) {
                                 self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, topMargin + self.postViewContainer.frame.size.height / 2);
                             }
                         }
                         completion:^(BOOL finished) {
                             if (newYAnimatedOrigin > bottomMargin)
                                 [self.postViewContainer setFrame:CGRectMake(0, bottomMargin, self.view.frame.size.width, scrollViewHeight)];

                             if (newYAnimatedOrigin < topMargin)
                                 [self.postViewContainer setFrame:CGRectMake(0, topMargin, self.view.frame.size.width, scrollViewHeight)];
                         }
         ];
    }
}

}

我使用了兩種不同的動畫,一種是默認慣性,另一種是當用戶高速甩動 containerView 時。

它在 iOS 7 下運行良好。

我從接受的答案的實現中獲得了靈感。 這是一個Swift 5.1 版本


邏輯:

  • 您需要計算平移手勢結束時的角度變化,並在無休止的計時器中不斷旋轉輪子,直到速度因減速率而磨損。
  • 在計時器的每次迭代中使用某個因素(例如 0.9)不斷降低當前速度。
  • 保持速度的下限以使計時器無效並完成減速過程。

用於計算減速度的主要函數:

// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025

private func animateWithInertia(velocity: Double) {
    _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
        guard let this = self else {
            return
        }
        let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
        let newVelocity = concernedVelocity * this.decelerationSmoothness
        this.currentVelocity = newVelocity
        var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
        if !this.isClockwiseRotation {
            angleTraversed *= -1
        }
        // exit condition
        if newVelocity < 0.1 {
            timer.invalidate()
            this.currentVelocity = 0.0
        } else {
            this.traverseAngularDistance(angle: angleTraversed)
        }
    }
}

handlePanGesture 函數中包含輔助函數、擴展和上述函數的使用的完整工作代碼。

// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025

private let maximumRotationAngleInCircle = 360.0

private var currentRotationDegrees: Double = 0.0 {
    didSet {
        if self.currentRotationDegrees > self.maximumRotationAngleInCircle {
            self.currentRotationDegrees = 0
        }
        if self.currentRotationDegrees < -self.maximumRotationAngleInCircle {
            self.currentRotationDegrees = 0
        }
    }
}
private var previousLocation = CGPoint.zero
private var currentLocation = CGPoint.zero
private var velocity: Double {
    let xFactor = self.currentLocation.x - self.previousLocation.x
    let yFactor = self.currentLocation.y - self.previousLocation.y
    return Double(sqrt((xFactor * xFactor) + (yFactor * yFactor)))
}

private var currentVelocity = 0.0
private var isClockwiseRotation = false

@objc private func handlePanGesture(panGesture: UIPanGestureRecognizer) {
    let location = panGesture.location(in: self)

    if let rotation = panGesture.rotation {
        self.isClockwiseRotation = rotation > 0
        let angle = Double(rotation).degrees
        self.currentRotationDegrees += angle
        self.rotate(angle: angle)
    }

    switch panGesture.state {
    case .began, .changed:
        self.previousLocation = location
    case .ended:
        self.currentLocation = location
        self.animateWithInertia(velocity: self.velocity)
    default:
        print("Fatal State")
    }
}

private func animateWithInertia(velocity: Double) {
    _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
        guard let this = self else {
            return
        }
        let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
        let newVelocity = concernedVelocity * this.decelerationSmoothness
        this.currentVelocity = newVelocity
        var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
        if !this.isClockwiseRotation {
            angleTraversed *= -1
        }
        if newVelocity < 0.1 {
            timer.invalidate()
            this.currentVelocity = 0.0
            this.selectAtIndexPath(indexPath: this.nearestIndexPath, shouldTransformToIdentity: true)
        } else {
            this.traverseAngularDistance(angle: angleTraversed)
        }
    }
}

private func traverseAngularDistance(angle: Double) {
    // keep the angle in -360.0 to 360.0 range
    let times = Double(Int(angle / self.maximumRotationAngleInCircle))
    var newAngle = angle - times * self.maximumRotationAngleInCircle
    if newAngle < -self.maximumRotationAngleInCircle {
        newAngle += self.maximumRotationAngleInCircle
    }
    self.currentRotationDegrees += newAngle
    self.rotate(angle: newAngle)
}

上面代碼中使用的擴展:

extension UIView {
    func rotate(angle: Double) {
        self.transform = self.transform.rotated(by: CGFloat(angle.radians))
    }
}

extension Double {
    var radians: Double {
        return (self * Double.pi)/180
    }

    var degrees: Double {
        return (self * 180)/Double.pi
    }
}

暫無
暫無

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

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