ios – 是否可以在两个视图背景图像之间淡入淡出?

前端之家收集整理的这篇文章主要介绍了ios – 是否可以在两个视图背景图像之间淡入淡出?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道一些按钮是否可能导致从一个背景图像淡入另一个背景图像?我的以下代码导致从当前图像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,animations: {
        oldImageView.alpha = 0
        newImageView.alpha = 1
        },completion: { completed in
            self.backgroundImageView.image = newImage
            newImageView.removeFromSuperview()
            oldImageView.removeFromSuperview()
    })
}

解决方法

假设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")

希望这可以帮助.

猜你在找的iOS相关文章