在iOS中围绕一个轴点旋转ImageView

3

记录和旋转的寻找条

我有一个如下所示的应用屏幕,用于记录(最多30秒)音频。

  1. 在录制音频时,如何使点状圆形线上的小圆圈作平滑旋转的寻找条?
  2. 在小圆圈沿着线旋转时,如何填充虚线?

enter image description here

谢谢。

2个回答

2
答案是可以通过使用 PanGesture 或者自动使用 Timer 来实现。 1. 使用 UIPanGestureRecognizer: 您可以使用 UIPanGestureRecognizer 实现此功能。 circleView 是您的 mainView,而 nob 是另一个 viewimageView,它将在 circleView 外移动。
panGesture = UIPanGestureRecognizer(target: self, action: #selector(panHandler(_:)))
nob.addGestureRecognizer(panGesture)

Definition of panHandler(_ :)

@objc func panHandler(_ gesture: UIPanGestureRecognizer) {
    let point = gesture.location(in: self)
    updateForPoints(point)
}

以下是核心逻辑,它是如何工作的。

func updateForPoints(_ point: CGPoint) {

    /*
     * Parametric equation of circle
     * x = a + r cos t
     * y = b + r sin ⁡t
     * a, b are center of circle
     * t (theta) is angle
     * x and y will be points which are on circumference of circle
     *
               270
                |
            _   |   _
                |
     180 -------o------- 360
                |
            +   |   +
                |
               90
     *
     */

    let centerOffset =  CGPoint(x: point.x - circleView.frame.midX, y: point.y - circleView.frame.midY)

    let a: CGFloat = circleView.center.x
    let b: CGFloat = circleView.center.y
    let r: CGFloat = circleView.layer.cornerRadius - 2.5
    let theta: CGFloat = atan2(centerOffset.y, centerOffset.x)
    let newPoints = CGPoint(x: a + r * cos(theta), y: b + r * sin(theta))

    var rect = nob.frame
    rect.origin = newPoints
    nob.center = newPoints
}

2. 使用定时器自动移动

let totalSeconds: Int = 30 // You can change it whatever you want
var currentSecond: Int = 1
var timer: Timer?


func degreesToRadians(_ degree: CGFloat) -> CGFloat {
     /// Will convert the degree (180°) to radians (3.14)
     return degree * .pi / 180
}

func angleFromSeconds(_ seconds: Int) -> CGFloat {
     /// Will calculate the angle for given seconds
     let aSliceAngle = 360.0 / CGFloat(totalSeconds)
     let angle = aSliceAngle * CGFloat(seconds) - 90
     return angle
}

/// ------------- TIMER METHODS ------------- ///

func startTimer() {
     stopTimer()
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeDidUpdate(_ :)), userInfo: nil, repeats: true)
     timeDidUpdate(timer!)
}

func stopTimer() {
     currentSecond = 1
     timer?.invalidate()
     timer = nil
}

@objc func timeDidUpdate(_ t: Timer) {
      let angle = angleFromSeconds(currentSecond)
      let theta = degreesToRadians(angle)
      updateAngle(theta: theta, animated: true)
      currentSecond += 1

      if currentSecond > totalSeconds {
         self.stopTimer()
      }
}

/// --------------- MAIN METHOD -------------- ///
func updateAngle(theta: CGFloat, animated: Bool) {

     let a: CGFloat = circleView.center.x
     let b: CGFloat = circleView.center.y
     let r: CGFloat = circleView.layer.cornerRadius
     let newPoints = CGPoint(x: a + r * cos(theta), y: b + r * sin(theta))

     var rect = nob.frame
     rect.origin = newPoints

     if animated {
         UIView.animate(withDuration: 0.1, animations: {
         self.nob.center = newPoints

         /// Uncomment if your nob is not a circle and you want to maintain the angle too
         // self.nob.transform = CGAffineTransform.identity.rotated(by: theta)
         })
     }
     else {
         nob.center = newPoints

         /// Uncomment if your nob is not a circle and you want to maintain the angle too
         //nob.transform = CGAffineTransform.identity.rotated(by: theta)
     }
}

2
如果我理解正确的话,您想要一个漂亮的动画进度指示器。当然有很多方法可以实现这一点。我将提供一个稍微复杂的解决方案,它将为您提供完全控制动画的能力——在动画过程中改变速度,从不同的点开始,随时暂停,甚至还可以恢复动画。
1)让我们从一个完整的工作示例开始。我们需要几个属性:
class ViewController: UIViewController {

   var displayLink:CADisplayLink?
   var circlePathLayer = CAShapeLayer()
   var dottedLine = CAShapeLayer()
   var beginTime:TimeInterval?

2) 定义显示链接。这是一个非常快速的触发器,在每次显示刷新时发送事件-即每秒60次,它可以手动设置,而且此进度函数将处理您的进度视图的正确状态。

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .blue
    beginTime = Date().timeIntervalSinceReferenceDate
    displayLink = CADisplayLink(target: self, selector: #selector(progress))
    displayLink?.add(to: RunLoop.main, forMode: .defaultRunLoopMode)

3) 定义你的环形路径,应该遵循什么

let path = UIBezierPath(arcCenter: view.center, radius: view.center.x - 20, startAngle: -CGFloat.pi / 2, endAngle: CGFloat.pi * 2 - CGFloat.pi / 2, clockwise: true)

4) 定义虚线和线条的默认动画。这里有timeOffsetspeedbeginTime属性,遵循CAMediaTimming协议,我们暂时不需要进行任何动画,并将此图层的绘制设置为零 - 开始状态。

        dottedLine.timeOffset = 0
        dottedLine.speed = 0
        dottedLine.duration = 1
        dottedLine.beginTime = dottedLine.convertTime(CACurrentMediaTime(), from: nil)
        dottedLine.repeatCount = 1
        dottedLine.autoreverses = false

        dottedLine.fillColor = nil
        dottedLine.fillMode = kCAFillModeBoth
        dottedLine.strokeStart = 0.0
        dottedLine.strokeColor = UIColor.white.cgColor
        dottedLine.lineWidth = 5.0
        dottedLine.lineJoin = kCALineJoinMiter
        dottedLine.lineDashPattern = [10,10]
        dottedLine.lineDashPhase = 3.0
        dottedLine.path = path.cgPath

        let pathAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
        pathAnimation.duration = 1
        pathAnimation.isRemovedOnCompletion = false
        pathAnimation.autoreverses = true
        pathAnimation.values = [0, 1]
        pathAnimation.fillMode = kCAFillModeBoth
        dottedLine.add(pathAnimation, forKey: "strokeEnd")
        view.layer.addSublayer(dottedLine)

5) 对于小圆形同样适用

        let circlePath = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0), radius: 10, startAngle: 0, endAngle:CGFloat.pi * 2, clockwise: true)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.strokeColor = nil

        circlePathLayer.addSublayer(shapeLayer)
        circlePathLayer.timeOffset = 0
        circlePathLayer.speed = 0
        circlePathLayer.beginTime = circlePathLayer.convertTime(CACurrentMediaTime(), from: nil)
        circlePathLayer.duration = 1
        circlePathLayer.repeatCount = 1
        circlePathLayer.autoreverses = false
        circlePathLayer.fillColor = nil
        view.layer.addSublayer(circlePathLayer)

        let circleAnimation = CAKeyframeAnimation(keyPath: "position")
        circleAnimation.duration = 1
        circleAnimation.isRemovedOnCompletion = false
        circleAnimation.autoreverses = false
        circleAnimation.values = [0, 1]
        circleAnimation.fillMode = kCAFillModeBoth
        circleAnimation.path = path.cgPath
        circlePathLayer.add(circleAnimation, forKey: "position")        
}

6) 最后是进度函数,它经常被调用,在这个点上你会设置进度位置 - 在我的例子中设置为30秒,但你可以在这里添加一些条件来不改变时间偏移量 - 暂停,或以不同的量来处理速度改变它,或将其放回。

 @objc func progress() {
        let time = Date().timeIntervalSinceReferenceDate - (beginTime ?? 0)
        circlePathLayer.timeOffset = time / 30
        dottedLine.timeOffset = time / 30
    }

7) 在完成动画后,请不要忘记释放资源并使显示链接无效。

displayLink?.invalidate()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接