簡體   English   中英

iOS Swift - 如何使用 CABasicAnimation 和 CATransform3DRotate 進行 360 度翻轉 animation 與“m34”變換?

[英]iOS Swift - How to do 360 degree flip animation using CABasicAnimation and CATransform3DRotate with "m34" transform?

盡管我盡了最大的努力,但我無法弄清楚如何使用 CATransform3DRotate 從左到右進行 UIView 的全周期旋轉 animation 。 請注意,我已經可以使用 CABasicAnimation 將其旋轉 360 度,但沒有 CATransform3DRotate。 但是,我想使用.m34變換來獲得透視深度。 涉及 UIView.animate/transitions 的解決方案對我想要完成的工作沒有幫助。 任何幫助深表感謝。

編輯:我在 Stackoverflow 和其他地方進行了廣泛搜索,但沒有找到任何描述如何使用 CATransform3DRotate 進行 360 度旋轉的內容。 在那里尋求幫助,因為這是一個以前似乎沒有回答過的問題。 謝謝!

這是將 UIView 旋轉 180 度的代碼。

var transform = CATransform3DIdentity
transform.m34 = 1.0 / -200.0

let animation = CABasicAnimation(keyPath: "transform")
animation.toValue = CATransform3DRotate(transform, CGFloat( Double.pi), 0, 1, 0)
animation.duration = 0.8
animation.beginTime = 0.0
animation.fillMode = .forwards
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
cardView.layer.add(animation, forKey: "360flip")

在此處輸入圖像描述

在最后一個 cardView.layer.add(animation...) 行之前添加了兩行:

    animation.isCumulative = true
    animation.repeatCount = 2

不要問我花了多長時間才弄清楚這個……現在是凌晨 2 點,所以這會給你一個線索;)

干杯。

PS注意 - 因為你重復 animation 你不能使用.easeInEaseOut否則你會在 180º 處暫停,所以你會看到我也將它更改為線性。

您當前的代碼正在替換動畫層的整個變換,這意味着您不能對其應用透視變換。 您還遇到了結尾 state 在數學上與開頭 state 相同的問題,為了解決這個問題,您嘗試將動畫鏈接在一起,並使用填充模式,這使整個事情變得更加復雜。

首先,讓我們處理轉換。 要獲得您想要設置圖層變換的.m34的透視圖,您已經在執行以下操作:

var perspective = CATransform3DIdentity
perspective.m34 = 1 / -200
cardView.layer.transform = perspective

接下來,要僅觸摸圖層變換的旋轉,您可以使用比transform更精確的關鍵路徑:

let rotate = CABasicAnimation(keyPath: "transform.rotation.y")
rotate.fromValue = 0

這將使層變換的 rest 保持不變。

最后,當 animation 的結尾與開頭相同時,如何強制 animation 引擎注意到差異? 使用byValue

rotate.byValue = CGFloat.pi * 2

這會迫使圖層繞遠至 360 度,而不是停留在原來的位置的懶惰捷徑。

最終的完整代碼是:

var perspective = CATransform3DIdentity
perspective.m34 = 1 / -200
cardView.layer.transform = perspective
let rotate = CABasicAnimation(keyPath: "transform.rotation.y")
rotate.fromValue = 0
rotate.byValue = CGFloat.pi * 2
rotate.duration = 2
cardView.layer.add(rotate, forKey: nil)

給出這個結果:

帶透視的 360 度旋轉標簽

簡而言之,你需要兩組動畫。

查看我之前的答案https://stackoverflow.com/a/24990978/945906

暫無
暫無

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

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