Forked from russomarina/gist:d6cc489f517eb82428a92b93d687e74b
Last active
September 2, 2019 20:27
-
-
Save xfer/1db9ddf92c1b06ba7cafb075f5e61163 to your computer and use it in GitHub Desktop.
Accelerometer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreMotion | |
class ViewController: UIViewController { | |
@IBOutlet weak var wallpaper: UIImageView! | |
@IBOutlet weak var welcomeLabel: UILabel! | |
var motionManager: CMMotionManager! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
motionManager = CMMotionManager() | |
motionManager.startAccelerometerUpdates(to: .main, withHandler: updateImageView) | |
} | |
private func apply(accelerometerData acceleration: CMAcceleration, into view: UIView, multiplier: CGFloat) { | |
let yOffset = CGFloat(acceleration.y) * multiplier | |
let xOffset = CGFloat(acceleration.x) * multiplier | |
view.transform = CGAffineTransform(translationX: xOffset, y: yOffset) | |
} | |
func updateImageView(data: CMAccelerometerData?, error: Error?) { | |
if let accelerometerData = motionManager.accelerometerData { | |
apply(accelerometerData: accelerometerData.acceleration, into: wallpaper, multiplier: 100.0) | |
apply(accelerometerData: accelerometerData.acceleration, into: welcomeLabel, multiplier: 50.0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment