[英]How to animate CAGradientLayer for a navigation bar
我們的導航欄使用CAGradientLayer來產生漸變效果。 現在我們要漸變顏色動態變化
我們使用以下代碼來實現漸變效果
let gradientLayer = CAGradientLayer()
var updatedFrame = self.navigationController!.navigationBar.bounds
updatedFrame.size.height += UIApplication.shared.statusBarFrame.size.height
gradientLayer.frame = updatedFrame
gradientLayer.colors = [UIColor.green.cgColor, UIColor.blue.cgColor] // start color and end color
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0) // Horizontal gradient start
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.0) // Horizontal gradient end
UIGraphicsBeginImageContext(gradientLayer.bounds.size)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.navigationController!.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
我們試圖在此層上添加動畫,但是它不起作用
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0,0.5]
animation.toValue = [0,0.9]
animation.autoreverses = true
animation.repeatCount = Float.infinity
gradientLayer.add(animation,forKey: nil)
我注意到,這種設置漸變顏色的方法實際上是在設置背景圖像。 我認為這是動畫無法正常工作的原因,因為設置圖像是一種原子動作。
我搜索了其他設置漸變效果的方法,但是沒有運氣。 那么可以在導航欄上實現漸變效果動畫嗎?
我仍然沒有找到對導航欄的CAGradientLayer進行動畫處理的方法。 但是,如果您只是想簡單地在導航欄上添加動畫,而不關心它是否真的是導航欄的一部分,那么我找到了一種解決方法。
我沒有更改導航欄的圖層,而是在導航欄后面放置了一個UIView,該圖層的圖層具有漸變動畫。
// create a view
// set its size the same as the navigation bar
let gradientView = UIView(frame: CGRect(x:0,y:0,width:self.navigationController!.navigationBar.frame.size.width,height:(self.navigationController!.navigationBar.frame.size.height+UIApplication.shared.statusBarFrame.height)))
view.addSubview(gradientView)
// add animation on this view
let anAnimation = CABasicAnimation(keyPath: "backgroundColor")
anAnimation.duration = 1.5;
anAnimation.repeatCount = 1;
anAnimation.autoreverses = false;
animation.fromValue = [0,0.5]
animation.toValue = [0,0.9]
gradientView.layer.add(anAnimation,forKey: "backgroundColor")
// hide the navigation bar's background image
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.isTranslucent = true
就像在導航欄上添加動畫一樣(實際上不是)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.