2016-06-24 5 views
1

点滅するアニメーションを書き込もうとしていますが、そのタイミングが気になりません。 Iは遊び場で単純なバージョンを作った:UIView.animateKeyFramesWithDurationがスムーズにアニメ化されない

import UIKit 
import XCPlayground 
let v = UIView() 
v.frame.size = CGSize(width: 200, height: 200) 
v.backgroundColor = UIColor.redColor() 
v.layer.cornerRadius = 100 

UIView.animateKeyframesWithDuration(1, delay: 0, options: .Repeat, animations: { 
    UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.5, animations: { 
     v.alpha = 0.0 
    }) 
    UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { 
     v.alpha = 0.5 
    }) 
    }, completion: nil) 

XCPlaygroundPage.currentPage.liveView = v 

ビューは0から0.5までフェードアウトし、その後アニメーションを再開する前に、第2の完全なアルファで吃音に見えます。私はシミュレータで同じことに気づいた。

キーフレームの動作方法が不明ですか?

答えて

2

検査の結果、vビューのデフォルトのalpha1.0です。これは、アニメーションが1秒間に終了した後にもう一度alphaになるとアニメーションが繰り返されることを意味します。これを補うには、を実行する前にalpha0.0に設定することを検討してください。

更新:

あなたは4つの状態にアニメーションをあなたのコードを破ることができます。

  1. 先頭には、alpha1.0です。
  2. 最初のキーフレームでは、alpha0.0に0.5秒で変更されます。
  3. 2番目のキーフレームは、alphaを0.5秒で0.5に変更します。
  4. この時点で、アニメーションは終了しました。したがって、vビューは状態に戻り、アニメーションを繰り返します。

州はvビューが0.0秒で0.5から1.0に起こっているので、フルalphaの点滅が発生する場所です。しかし、コンピュータは0.0秒で何も起きることはできません。複雑な物理現象のため実際には可能ではありません。その結果、コンピュータは0.0秒にできるだけ近づくように、alphaの分割秒点滅になります。あなたはそのための方法は、アニメーションの状態がその状態の結果と同じになります、またはあなたがalpha背中をもたらす別のキーフレームを追加することができます0.5に元alphaを設定するか、これを回避するには

例:

オプション1:

0.0にアニメーションが終わる前に
//Import Statements 
//Configuration and Initialization of v view 

v.alpha = 0.5 //<--- This is the key point 

UIView.animateKeyframesWithDuration(1, delay: 0, options: .Repeat, animations: { 
    UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.5, animations: { 
     v.alpha = 0.0 
    }) 
    UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { 
     v.alpha = 0.5 
    }) 
}, completion: nil) 

XCPlaygroundPage.currentPage.liveView = v 

オプション2:

//Import Statements 
//Configuration and Initialization of v view 
v.alpha = 0.0 //<-- Make sure to set the original alpha to 0.0 

let duration: NSTimeInterval = 1.8 
let third: NSTimeInterval = 1/3 

UIView.animateKeyframesWithDuration(duration, delay: 0, options: .Repeat, animations: { 
    UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: third, animations: { 
     v.alpha = 0.0 
    }) 
    UIView.addKeyframeWithRelativeStartTime(third, relativeDuration: third, animations: { 
     v.alpha = 0.5 
    }) 
    //Key Point Below. Added Another Frame! 
    UIView.addKeyframeWithRelativeStartTime(third*2, relativeDuration: third, animations: { 
     v.alpha = 0.0 
    }) 
}, completion: nil) 

XCPlaygroundPage.currentPage.liveView = v 
+0

Iは、元のアルファは、それが反復間でその値にスナップバックなぜ思ったんだけど1であったことがわかります。私はその行動が驚くべきことを発見した。私はCAAnimationsが完了したら削除されていることを知っています、それは基本的にちょうどそれを避けるための方法ですか? –

+0

@ThomasAbendは、改善された説明と可能な解決方法については、私のアップデートを参照してください。 – Ike10

関連する問題