繁体   English   中英

在iOS中的轴心点周围旋转ImageView

[英]Rotate a ImageView around a pivot point in iOS

记录和旋转搜索栏

我有一个App屏幕,可以录制(最多30秒)音频。

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

在此输入图像描述

谢谢。

答案有两种方法可以使用PanGesture并自动使用Timer

1.使用UIPanGestureRecognizer:

您可以使用UIPanGestureRecognizer实现此UIPanGestureRecognizer circleView是你mainViewnob是另一种viewimageView将外移到circleView

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

panHandler(_ :)定义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.使用Timer自动移动

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)让我们从完整的工作示例开始。 我们需要很少的属性:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM