问题描述
我正在尝试在我的一个视图中创建翻转动画。我设法使动画正常工作,但它看起来很糟糕,因为卡片(具有白色背景颜色)在动画期间将其颜色变暗以变暗。
不知道有没有办法去掉这种暗淡的效果,在整个动画过程中保持卡片的原始颜色?
为了进一步参考,请在下面找到一个简单的视图控制器来重现我的问题。
import UIKit
class ViewController: UIViewController {
private lazy var cardView: UIView = {
let backgroundView = UIView(frame: CGRect(x: 0,y: 0,width: 300,height: 200))
backgroundView.backgroundColor = .white
return backgroundView
}()
private lazy var flipButton: UIButton = {
let flipButton = UIButton(frame: CGRect(x: 0,height: 200))
flipButton.setTitle("Flip",for: .normal)
flipButton.setTitleColor(.red,for: .normal)
flipButton.addTarget(self,action: #selector(flipCard),for: .touchUpInside)
return flipButton
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .lightGray
view.addSubview(cardView)
cardView.addSubview(flipButton)
cardView.center = view.center
}
@objc
func flipCard() {
UIView.transition(with: cardView,duration: 10,options: .transitionFlipFromright,animations: nil,completion: nil)
}
}
解决方法
你可以使用
UIView.animateKeyframes(withDuration: 6,delay: 0,options: []) {
UIView.addKeyframe(withRelativeStartTime: 0,relativeDuration: 0.5) {
self.cardView.transform3D = CATransform3DRotate(self.cardView.layer.transform,CGFloat.pi,1,0)
}
UIView.addKeyframe(withRelativeStartTime: 0.5,relativeDuration: 1) {
self.cardView.transform3D = CATransform3DRotate(self.cardView.layer.transform,0)
}
}
代替
UIView.transition(with: cardView,duration: 10,options: .transitionFlipFromRight,animations: nil,completion: nil)
,
您也可以在 Swift 5 中通过 UIView.animate(),
UIView.animate(withDuration: duration/2,options: .curveLinear) {
targetView.transform = CGAffineTransform.identity.rotated(by: .pi )
} completion: { (_) in
UIView.animate(withDuration: duration/2,options: .curveLinear) {
targetView.transform = CGAffineTransform.identity.rotated(by: .pi * 2)
}
}