[英]Why does CGFloat casted from Float not exhibit CGFloat behavior?
I have this simple example where I try to draw a circle. 我有一个简单的示例,尝试绘制一个圆。 This code below does not give me a circle. 下面的这段代码不会给我一个圆圈。
import UIKit
class PlayingCardView: UIView {
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext(){
context.addArc(center: CGPoint(x: bounds.midX,
y: bounds.midY), radius: 100.0,
startAngle: 0,
endAngle: CGFloat(2.0*Float.pi),
clockwise: true)
context.setLineWidth(5.0)
UIColor.red.setStroke()
context.strokePath()
print(2.0*CGFloat.pi)
print(CGFloat(2.0*Float.pi))
}
}
}
This is what I get with the above code: 这就是上面的代码:
with output: 输出:
6.283185307179586 6.283185005187988
from the print statements which correspond to 2.0*CGFloat.pi
and CGFloat(2.0*Float.pi)
respectively. 从分别对应于2.0*CGFloat.pi
和CGFloat(2.0*Float.pi)
的打印语句中。
Updating the code to this (I only change the endAngle in context.addArc
to be 2.0*CGFloat.pi
instead of CGFloat(2.0*Float.pi)
将代码更新为此(我仅将context.addArc
的endAngle更改为2.0*CGFloat.pi
而不是CGFloat(2.0*Float.pi)
import UIKit
class PlayingCardView: UIView {
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext(){
context.addArc(center: CGPoint(x: bounds.midX,
y: bounds.midY), radius: 100.0,
startAngle: 0,
endAngle: 2.0*CGFloat.pi,
clockwise: true)
context.setLineWidth(5.0)
UIColor.red.setStroke()
context.strokePath()
print(2.0*CGFloat.pi)
print(CGFloat(2.0*Float.pi))
}
}
}
I get this drawing (The circle is there) 我得到了这张图 (圆圈在那里)
There is obviously a difference between the casted CGFloat from Float and CGFloat. 从Float铸造的CGFloat与CGFloat之间显然存在差异。 Does anybody know what it is and why this behavior is useful in Swift? 有人知道它是什么,为什么这种行为在Swift中有用吗?
On a 64-bit platform, CGFloat
is (essentially) Double
, a 64-bit floating point number, whereas Float
is a 32-bit floating point number. 在64位平台上, CGFloat
(本质上)是Double
(64位浮点数),而Float
是32位浮点数。
So 2.0*Float.pi
is “2π with 32-bit precision”, and converting that to the 64-bit quantity CGFloat
preserves the value, without increasing the precision. 因此2.0*Float.pi
为“具有32位精度的2π”,并将其转换为64位量CGFloat
保留该值,而不会提高精度。
That is why 2.0*CGFloat.pi != CGFloat(2.0*Float.pi)
. 这就是为什么2.0*CGFloat.pi != CGFloat(2.0*Float.pi)
。 The former is “2π with 64-bit precision”, and is what you should pass to the drawing functions. 前者是“具有64位精度的2π”,是传递给绘图函数的内容。
In your particular case, CGFloat(2.0*Float.pi)
is a tiny bit smaller than 2.0*CGFloat.pi
, so that only an invisibly short arc is drawn (from radians 0.0 to approximately -0.00000003). 在您的特定情况下, CGFloat(2.0*Float.pi)
比2.0*CGFloat.pi
小一点,因此只绘制了一个看不见的短弧(从弧度0.0到大约-0.00000003)。
For a full circle you can alternatively use 对于完整的圈子,您也可以使用
let radius: CGFloat = 100.0
context.addEllipse(in: CGRect(x: bounds.midX - radius, y: bounds.midY - radius,
width: 2.0 * radius, height: 2.0 * radius))
and avoid all rounding problems. 并避免所有舍入问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.