1

我正在尝试制作一个应用程序,它将根据设备的倾斜角度改变背景颜色。我找到设备的倾斜值没有问题,我似乎无法将倾斜值用作 UIColor 中的参数。

我有以下代码:

let manager = CMMotionManager()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    manager.gyroUpdateInterval = 0.1
    manager.startGyroUpdates()

    if manager.deviceMotionAvailable {
        manager.deviceMotionUpdateInterval = 0.01
        manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) {
            [weak self] (data: CMDeviceMotion!, error: NSError!) in

            let xColor = data.gravity.x


            self!.view.backgroundColor = UIColor(red: 155/255, green: xColor, blue: 219/255, alpha: 1)
        }
    }

}

您可能会认为它会根据设备的 x 倾斜度生成不同的颜色,但事实并非如此。不支持该类型。

Does anybody know how I could use the "xColor" variable to change the green level of the background color?

4

1 回答 1

2

问题是 data.gravity.x 返回一个 Double 并且 UIColor 期望 CGFloat 值介于 0.0 和 1.0 之间。您需要将 Double 转换为 CGFloat 并使用 abs() 方法从负数中提取正数。

import UIKit
import CoreMotion
class ViewController: UIViewController {
    let motionManager = CMMotionManager()
    override func viewDidLoad() {
        super.viewDidLoad()
        motionManager.gyroUpdateInterval = 0.1
        motionManager.startGyroUpdates()
        if motionManager.deviceMotionAvailable {
            motionManager.deviceMotionUpdateInterval = 0.01
            motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data: CMDeviceMotion!, error: NSError!) -> Void in
                let x = data.gravity.x
                let y = data.gravity.y
                let z = data.gravity.z
                self.view.backgroundColor = UIColor(
                    red: CGFloat(abs(x)),
                    green: CGFloat(abs(y)),
                    blue: CGFloat(abs(z)),
                    alpha: 1.0)
            })
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
于 2015-04-26T04:26:54.293 回答