如何在swift中将Int32值转换为CGFloat?

时间:2014-11-27 12:36:10

标签: swift ios8.1 cgfloat int32

这是我的代码。我将两个值传递给CGRectMake(..)并获取和错误。

let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width
// return Int32 value

let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height
// return Int32 value

myLayer?.frame = CGRectMake(0, 0, width, height)
// returns error: '`Int32`' not convertible to `CGFloat`

如何将Int32转换为CGFloat以不返回错误?

2 个答案:

答案 0 :(得分:63)

要在数值数据类型之间进行转换,请创建目标类型的新实例,并将源值作为参数传递。所以要将Int32转换为CGFloat

let int: Int32 = 10
let cgfloat = CGFloat(int)

在您的情况下,您可以这样做:

let width = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width)
let height = CGFloat(CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height)

myLayer?.frame = CGRectMake(0, 0, width, height)

或:

let width = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).width
let height = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription as CMVideoFormatDescriptionRef!).height

myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height))

请注意,swift中的数值类型之间没有隐式或显式类型转换,因此您还必须使用相同的模式将Int转换为Int32或转换为UInt

答案 1 :(得分:2)

使用width初始值设定项明确地将heightCGFloat转换为CGFloat's

myLayer?.frame = CGRectMake(0, 0, CGFloat(width), CGFloat(height))