Converting Int to CGFloat results in 0.000000

谁说我不能喝 提交于 2019-12-25 02:26:10

问题


I am attempting to take Int values from an Array and convert them into CGFloats so that I may create a UIColor from those red, green, and blue values. Simple enough, right?

I can successfully get the Int values out of the array, but when I attempt to convert to CGFloat, the result is 0.000000. Why is this?

let colorArray = NSUserDefaults.standardUserDefaults().arrayForKey("colors")
let redValue = colorArray[0] as Int
let greenValue = colorArray[1] as Int
let blueValue = colorArray[2] as Int
NSLog("%i", redValue) //prints 255
NSLog("%i", greenValue) //prints 250
NSLog("%i", blueValue) //prints 150
let redFloat = CGFloat(redValue) / 255.0
let greenFloat = CGFloat(greenValue) / 255.0
let blueFloat = CGFloat(blueValue) / 255.0
NSLog("%f", redFloat) //prints 0.000000
let color = UIColor(red: redFloat, green: greenFloat, blue: blueFloat, alpha: 1)

If I don't divide by 255.0 I get the same result - 0. What am I doing wrong here?


回答1:


This seems to be a weird problem with Foundation string formatting and conversion from CGFloat. The same problem occurs with NSString(format:_:). If you use NSLog("%f", redFloat.native) or print("\(redFloat)") or just print(redFloat) there are no problems.



来源:https://stackoverflow.com/questions/25098678/converting-int-to-cgfloat-results-in-0-000000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!