【问题标题】:Rotating a UIView to point at another UIView旋转 UIView 以指向另一个 UIView
【发布时间】:2017-08-05 09:39:38
【问题描述】:

我试图让一个名为objectUIView 旋转以指向另一个名为origUIView 的中心。我似乎无法正确计算角度。我的三角函数有点生锈,所以我无法弄清楚我的数学是怎么错的。

let y0 = object.center.y
let y1 = orig?.center.y
let x0 = object.center.x
let x1 = orig?.center.x

let angle = atan2((y1! - y0), (x1! - x0)) * 180 / CGFloat.pi
rotateTo(object: object, degrees: angle, time: deplexed[1] as! CGFloat)

【问题讨论】:

    标签: swift uiview rotation transform


    【解决方案1】:

    使旋转器的顶部视点对准目标点。

    let direction = CGPoint(x: targetPoint.x - rotatorView.center.x, y: targetPoint.y - rotatorView.center.y)
    var angle = atan2(direction.y, direction.x)
    rotatorView.transform = CGAffineTransform(rotationAngle: angle + .pi/2)
    

    如果点在右边,atan2 返回零。

    如果要将atan2结果转换为度数:

    if angle < 0 {
        angle += .pi * 2
    }
    let degrees = angle * 180.0/.pi
    

    如果角度为负,则添加一个完整的圆。 0 度指向右侧。

    【讨论】:

      【解决方案2】:

      创建一个默认对象并假设它是一个按钮:

      let button = UIButton()
      
      if button.transform == CGAffineTransform.identity {
      
          UIView.animate(withDuration: 0.5, animations: {
      
              button.transform = CGAffineTransform(rotationAngle: self.radians(degrees: 180))
      
          })
      
      } else {
      
           UIView.animate(withDuration: 0.5, animations: {
      
           button.transform = CGAffineTransform.identity
      
           })
      }
      
      func radians(degrees: CGFloat) -> CGFloat {
      
          return CGFloat(degrees * CGFloat.pi / degrees)       
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-09
        • 2017-12-14
        • 2019-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多