2016-04-03 64 views
5

我想知道是否有可能使某個按鈕導致從一個背景圖像淡入到另一個背景圖像?下面的代碼導致我從當前圖像background-image-1突然改變爲新圖像background-image-2是否有可能在兩個視圖背景圖像之間淡入淡出?

func buttonPressed() { 
    if let image = UIImage(named: "background-image-2") { 
     UIView.animateWithDuration(2, delay: 0, options: .CurveEaseInOut, animations: {_ in 
      self.view.backgroundColor = UIColor(patternImage: image) 
     }, completion: nil) 
} 

感謝

編輯

雖然接受的答案沒有工作,我在圖像之間快速切換時發現輕微毛刺。使用UIView.animateWithDuration類似的方法解決了這一:

func buttonPressed() { 
    let oldImageView = UIImageView(image: UIImage(named: "background-image-1")) 
    oldImageView.frame = view.frame 
    let newImageView = UIImageView(image: UIImage(named:"background-image-2")) 
    newImageView.frame = view.frame 
    newImageView.alpha = 0 
    view.insertSubview(newImageView, aboveSubview: backgroundImageView) 
    view.insertSubview(oldImageView, aboveSubview: newImageView) 
    UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseInOut, animations: { 
     oldImageView.alpha = 0 
     newImageView.alpha = 1 
     }, completion: { completed in 
      self.backgroundImageView.image = newImage 
      newImageView.removeFromSuperview() 
      oldImageView.removeFromSuperview() 
    }) 
} 

回答

6

imageView是您用於動畫的UIImageView。 image1是你的原始圖像。 image2是新圖像。試試這個:

let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents") 
crossFade.duration = 1 
crossFade.fromValue = image1.CGImage 
crossFade.toValue = image2.CGImage 
self.imageView.image = image2 
self.imageView.layer.addAnimation(crossFade, forKey: "animateContents") 

希望這會有所幫助。

+0

感謝您的建議。我試圖在我的**編輯**部分的問題。不幸的是,這不起作用。任何建議爲什麼,請嗎? – Alex

+0

這是因爲您的imageView沒有正確創建。在視圖確實出現的方法中,將imageView的中心設置爲視圖的中心,並將其大小設置爲視圖的大小。 – penatheboss

+0

是的,發現了,對不起。請參閱修改。 – Alex

0

的背景顏色被認爲是一個動畫的屬性,但圖案顏色必須不工作。

實際上是否需要圖案顏色,或者是否使用該顏色作爲視圖的背景插入圖像而不使用重複圖案?

+0

我使用'圖案顏色:'爲了插入圖像和視圖的背景。目的是淡出這個圖像,並用'background-image-2'代替它。謝謝 – Alex

+1

我最好只是將它作爲子視圖插入並以此方式進行動畫製作?例如http://stackoverflow.com/questions/25026621/fade-animation-for-uiimages-in-swift – Alex