簡體   English   中英

如何設置 UIView 按度旋轉

[英]How to set UIView rotation by degrees

我試圖通過旋轉 UIImageView 對象來反映 iOS 應用程序中的加速度計數據。 目前,我正在根據對象當前位置讀數和先前位置讀數之間的差異來旋轉對象(例如,如果加速度計處於 90 度,而現在處於 80 度,它將旋轉對象 -10 度)。 但是這種方法有問題,因為加速度計中有未讀的變化。

因此,我想根據加速度計的度數方向設置 UIImageView 的旋轉 例如,如果加速度計讀數為 65 度,我想將 UIImageView 對象的方向設置為 65 度。 有沒有辦法做到這一點?

此外,我希望旋轉動畫。

這是我當前的代碼,它根據先前閱讀的更改旋轉圖像視圖對象:

// UIImage view declaration
@IBOutlet weak var visualizer: UIImageView! 

// Rotation code where 'deg' is the change in rotation from the previous reading
UIView.animate(withDuration: 1.0, delay: 0, options: .curveLinear, animations: { () -> Void in self.visualizer.transform = self.visualizer.transform.rotated(by: CGFloat(truncating: deg))})

請注意,我將更改代碼的另一部分,以便 'deg' 將是加速度計的方向(以度為單位),而不是度數的變化。

旋轉基於弧度,所以你只需要做數學

let radian = degree * CGFloat.pi / 180

使用 CGAffineTransform 將對象旋轉到 n 度

 view.transform = CGAffineTransform(rotationAngle: (degree * CGFloat.pi / 180))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM