2017-10-08 96 views
1

我一直在試圖創建一個模擬投擲硬幣的動畫。這是我目前使用的,但是每個動畫執行之間有一個小小的延遲,我不認爲UIView.transition是實現它的最佳方式。如何製作連續翻轉動畫?

var duration: CGFloat = 0.25 
var imageIndex = 1 
var repeatCount = 0 

@objc func handleSpin() 
{ 
    let options: UIViewAnimationOptions = .transitionFlipFromLeft 

    UIView.transition(with: self.coinImageView, duration: TimeInterval(duration), options: options, animations: nil) { (completed) in 

     if self.repeatCount == 10 
     { 
      self.duration = 0.25 
      self.imageIndex = 1 
      self.repeatCount = 0 
      return 
      //animation done 
     } 
     else 
     { 
      self.coinImageView.image = UIImage(named: self.imageNames[self.imageIndex]) 
      self.duration += 0.075 
      self.repeatCount += 1 
      self.imageIndex = self.imageIndex == self.imageNames.count - 1 ? 0 : self.imageIndex + 1 
      self.handleSpin() 
     } 
    } 

該函數自己調用10次,每次都會增加一點動畫持續時間。但正如我所說的那樣,問題在於我想要修復的每次執行之間有一點點延遲。

我也試圖與CATransition,並將其添加到ImageView的像這樣的層:

func flipAnimation() 
{ 
    let animation = CATransition() 
    animation.type = "flip" 
    animation.startProgress = 0 
    animation.endProgress = 0.5 
    animation.subtype = "fromLeft" 
    animation.duration = 0.5 
    animation.repeatCount = 0 

    self.layer.add(animation, forKey: "animation") 
} 

這裏的問題是,我不能讓圖像保持翻轉,因爲它恢復到當動畫完成時默認,而且我不知道如何跟蹤動畫何時完成。

有沒有第三個更好的方法呢?

編輯:我應該提到,我也嘗試過使用Spring庫,但它有與CATransition相同的問題;當動畫完成後,圖像恢復到正常狀態,我找不到任何防止這種情況的方法。

+0

添加您想要的動畫樣本以及您從代碼中獲得的動畫。 –

+0

好的,我會盡快上傳一段短片。 – Elhoej

+0

檢查答案https://stackoverflow.com/a/22549926/2963352 – vivek

回答

0

你可以嘗試動畫關鍵幀,這也許會更好看:

extension UIView { 
    func startAnimatingFlip(with duration: TimeInterval) { 
     UIView.setAnimationCurve(.linear) 
     UIView.animateKeyframes(withDuration: duration/2, delay: 0, options: .beginFromCurrentState, animations: { 
      UIView.setAnimationCurve(.linear) 
      UIView.addKeyframe(withRelativeStartTime: duration/2, relativeDuration: 0.5, animations: { 
       self.transform = CGAffineTransform(scaleX: -1, y: 1) 
      }) 
      UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations: { 
       self.transform = CGAffineTransform(scaleX: 1, y: 1) 
      }) 
     }) { _ in 
      self.startAnimatingFlip(with: duration) 
     } 
    } 
} 

當然,你必須把它調整到您的需要。但就動畫而言,關鍵幀之間似乎沒有任何延遲。