将Int转换为CGFloat会产生0.000000 [英] Converting Int to CGFloat results in 0.000000
问题描述
我正在尝试从数组中获取 Int
值并将它们转换为 CGFloat
s以便我可以创建来自红色,绿色和蓝色值的 UIColor
。很简单吧?
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?
我可以成功地从数组中获取 Int
值,但是当我尝试转换为<$ c时$ c> CGFloat ,结果为0.000000。这是为什么?
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)
如果我不除以255.0我得到了相同的结果 - 0.我在这里做错了什么?
If I don't divide by 255.0 I get the same result - 0. What am I doing wrong here?
推荐答案
这似乎是基金会的一个奇怪问题字符串格式和从 CGFloat
转换。 NSString(格式:_:)
也会出现同样的问题。如果您使用 NSLog(%f,redFloat.native)
或 print(\(redFloat))
或只是 print(redFloat)
没有问题。
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.
这篇关于将Int转换为CGFloat会产生0.000000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!