2017-03-06 156 views
0

我想在Swift中使用CoreMotion(加速度計)在2 UIImages之間切換。傾斜iPhone更改UIImage(加速度計)

我已經實現了兩個圖像之間的平滑淡入淡出過渡效果,我目前正在使用一個按鈕來實例化這種效果。想用加速度計代替它,所以你可以控制效果如何處理。

@IBAction func TapToFade(_ sender: AnyObject) { 
     let image1:UIImage = UIImage(named: "ImageA")!; 
     let image2:UIImage = UIImage(named: "ImageB")!; 
     let crossFade:CABasicAnimation = CABasicAnimation(keyPath: "contents"); 
     crossFade.duration = 3.0; 
     crossFade.beginTime = 0.0; 
     crossFade.fromValue = image1.cgImage; 
     crossFade.toValue = image2.cgImage; 
     imageView.layer.add(crossFade, forKey:"animateContents"); 

     if crossFade.beginTime < 5.0 { 
      imageView.image = image2; 

     } 
    } 

回答

0

確保您的設備縱向鎖定設置爲關閉控制中心,嘗試下面的代碼。

@IBOutlet weak var imageView: UIImageView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

UIDevice.current.beginGeneratingDeviceOrientationNotifications() 
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.detectMotion),name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) 
} 


func detectMotion(){ 
    let device = UIDevice.current 
    switch device.orientation{ 
    case .portrait: 

     let crossFade:CABasicAnimation = CABasicAnimation(keyPath: "contents"); 
     crossFade.duration = 3.0; 
     crossFade.beginTime = 0.0; 
     crossFade.fromValue = UIImage(named: "ImageB.jpg")?.cgImage 
     crossFade.toValue = UIImage(named: "ImageA.jpg")?.cgImage 
     imageView.layer.add(crossFade, forKey:"animateContents"); 

     if crossFade.beginTime < 5.0 { 
      imageView.image = UIImage(named: "ImageA.jpg") 
     } 

    case .faceUp: 

     let crossFade:CABasicAnimation = CABasicAnimation(keyPath: "contents"); 
     crossFade.duration = 3.0; 
     crossFade.beginTime = 0.0; 
     crossFade.fromValue = UIImage(named: "ImageA.jpg")?.cgImage 
     crossFade.toValue = UIImage(named: "ImageB.jpg")?.cgImage 
     imageView.layer.add(crossFade, forKey:"animateContents"); 

     if crossFade.beginTime < 5.0 { 
      imageView.image = UIImage(named: "ImageB.jpg") 
     } 

    default: 
     print("unknown") 

    } 
}