问题
I am attempting to take Int
values from an Array and convert them into CGFloat
s 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