Ios 使用swift中的参数倾斜值数据生成UIColor
我正在尝试制作一个应用程序,它可以根据设备的倾斜角度改变背景的颜色。我在查找设备的倾斜值方面没有问题,我只是不能在UIColor中使用倾斜值作为参数 我有以下代码:Ios 使用swift中的参数倾斜值数据生成UIColor,ios,iphone,swift,motion,tilt,Ios,Iphone,Swift,Motion,Tilt,我正在尝试制作一个应用程序,它可以根据设备的倾斜角度改变背景的颜色。我在查找设备的倾斜值方面没有问题,我只是不能在UIColor中使用倾斜值作为参数 我有以下代码: let manager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.
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倾斜角度而变化,但事实并非如此。不支持该类型
有人知道如何使用“xColor”变量来更改背景色的绿色级别吗?问题在于data.gravity.x返回一个双精度值,而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.
}
}