gpt4 book ai didi

ios - 计算旋转速度自然旋转view iOS

转载 作者:搜寻专家 更新时间:2023-10-30 21:58:50 27 4
gpt4 key购买 nike

我有一个圆形 View ,并通过以下代码覆盖 touchesBegan(touches:, withEvent:)touchesMoved(touches:, withEvent:) 使其旋转.

var deltaAngle = CGFloat(0)
var startTransform: CGAffineTransform?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touchPoint = touches.first!.locationInView(view)

let dx = touchPoint.x - view.center.x
let dy = touchPoint.y - view.center.y

deltaAngle = atan2(dy, dx)
startTransform = arrowPickerView.transform
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touchPoint = touches.first!.locationInView(view)

let dx = touchPoint.x - view.center.x
let dy = touchPoint.y - view.center.y
let angle = atan2(dy, dx)
let angleDifference = deltaAngle - angle
let transform = CGAffineTransformRotate(startTransform!, -angleDifference)
arrowPickerView.transform = transform
}

我想覆盖 touchesEnded(touches:, withEvent:) 来计算速度并让 View 自然旋转一点(类似于连续滚动)。我目前保存原始变换并计算增量角。我该如何实现?提前致谢!

最佳答案

在我下面的示例中,CGAffineTransformRotate 取决于:

  • 方向(如果用户从左向右、向上或向下等移动)
  • 旋转(取决于 touchesBegan 和 touchesEnded 之间的时间的因素)
  • 负责人

这将创建一个 CGAffineTransformRotate 并以持续时间 1 (s) 旋转,以创建动态滚动的感觉,使用 UIViewAnimationOptions.CurveEaseOut 属性

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touchPointEnd = touches.first!.locationInView(view)

self.dateTouchesEnded = NSDate()

let delay : NSTimeInterval = NSTimeInterval(0)

let timeDelta : Double = self.dateTouchesEnded!.timeIntervalSince1970 - self.dateTouchesStarted!.timeIntervalSince1970

let horizontalDistance : Double = Double(touchPointEnd.x - self.touchPointStart!.x)
let verticalDistance : Double = Double(touchPointEnd.y - self.touchPointStart!.y)

var direction : Double = 1
if (fabs(horizontalDistance) > fabs(verticalDistance)) {
if horizontalDistance > 0 {
direction = -1
}
} else {
if verticalDistance < 0 {
direction = -1
}
}

let rotation : Double = (0.1 / timeDelta < 0.99) ? 0.1 / timeDelta : 0.99

let duration : NSTimeInterval = NSTimeInterval(1)
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
let transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(direction) * CGFloat(rotation) * CGFloat(M_PI))
self.imageView.transform = transform
}, completion: nil)

}

我添加了变量来跟踪触摸的开始和结束时间,并添加了 touchesBegan 函数的 CGPoint 位置

var dateTouchesStarted : NSDate?
var dateTouchesEnded : NSDate?
var touchPointStart : CGPoint?

在 touchesBegan 中我添加了:

self.touchPointStart = touchPoint

如上所述设置变量。

关于ios - 计算旋转速度自然旋转view iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367828/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com