围绕iOS

时间:2018-04-19 11:26:53

标签: ios swift

记录并旋转搜索栏

我在下面有一个应用程序屏幕,可录制(最多30秒)音频。

  1. 在录制音频的同时,如何在虚线圆圈线上将小圆圈作为搜索条平滑旋转?
  2. 当小圆圈沿着线旋转时,如何填充虚线。
  3. enter image description here

    感谢。

2 个答案:

答案 0 :(得分:2)

  

使用PanGesture并自动使用Timer,答案有两种方法。

<强> 1。使用UIPanGestureRecognizer:

您可以使用UIPanGestureRecognizer来实现此目的。 circleViewmainViewnob是另一个viewimageView,它将移出circleView

panGesture = UIPanGestureRecognizer(target: self, action: #selector(panHandler(_:)))
nob.addGestureRecognizer(panGesture)

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

答案 1 :(得分: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)为线条定义虚线和默认动画。 CAMediaTimming协议之后有timeOffsetspeedbeginTime属性,我们还不想动画任何东西,并将此图层的绘图设置为零 - 开始状态

        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()
相关问题