倾斜iPhone改变UIImage(加速度计)

时间:2017-03-06 11:47:24

标签: iphone swift uiimage accelerometer core-motion

我正试图在Swift中使用CoreMotion(加速度计)在2个UIImages之间切换。

我已经在两个图像之间实现了平滑的淡入淡出过渡效果,我现在正在使用Button来实例化这种效果。想用加速度计替换它,这样你就可以控制效果的处理方式。

    @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;

        }
    }

1 个答案:

答案 0 :(得分: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")

    }
}