我有一个UIImageView,我想这样,当我调用一个函数时,图像从平面(正常状态),到倾斜到右旋转(比如可能是20度旋转),然后回到它是平坦的(正常)状态。
这就是我现在所拥有的,但我无法获得理想的结果。
extension UIView {
func rotate(duration: CFTimeInterval = 2) {
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0.0
rotateAnimation.toValue = CGFloat(20)
rotateAnimation.isRemovedOnCompletion = true
rotateAnimation.duration = duration
rotateAnimation.repeatCount=Float.infinity
self.layer.add(rotateAnimation, forKey: nil)
}
}
UIImageView.rotate()
答案 0 :(得分:6)
我尝试了创建上面的动画,我尝试过的代码就在这里
必需的声明
///View Outlet - Image or UIView
@IBOutlet weak var baseView: UIImageView!
/// Timer - To make Animation in repititive State
var newNAimationTimer : Timer?
/// Plus Degree
let degrees : CGFloat = 20.0
/// Minus Degree
let minusDegree : CGFloat = -20.0
计时器功能
//MARK: Start Timer
func startTimer()
{
/// Start timer if Timer is Not Initialised Before
if newNAimationTimer == nil {
/// Assign Timer
newNAimationTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(animationVC.animateView), userInfo: nil, repeats: true)
}
}
//MARK: Stop Timer
func stopTimer()
{
///Check Do timer is Initialised
if newNAimationTimer != nil {
/// Yes Stop
newNAimationTimer?.invalidate()
}
}
计时器处理程序
/// Animate View With Animations
@objc func animateView()
{
let plusRadian : CGFloat = degrees * CGFloat((Double.pi/180))
let minusRadian : CGFloat = minusDegree * CGFloat((Double.pi/180))
/// First Animation To make View Goes clockwise
UIView.animate(withDuration: 0.5, animations: {
self.baseView.transform = CGAffineTransform(rotationAngle: plusRadian)
}) { (success) in
/// Second Animation to make view go antiClockWise
UIView.animate(withDuration: 0.5, animations: {
self.baseView.transform = CGAffineTransform(rotationAngle: minusRadian)
})
}
}
按钮操作
@IBAction func animationButton(_ sender: Any) {
/// Start the Animation
startTimer()
}
<强>截图强>