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

ios*_*ner 25 int32 cgfloat swift ios8.1

在这里我的代码.我正在传递两个值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`
Run Code Online (Sandbox Code Playgroud)

如何转换Int32CGFloat不返回错误?

Ant*_*nio 67

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

let int: Int32 = 10
let cgfloat = CGFloat(int)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

要么:

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))
Run Code Online (Sandbox Code Playgroud)

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