简体   繁体   English

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

[英]how to convert Int32 value to CGFloat in swift?

Here my code. 在这里我的代码。 I am passing two values into CGRectMake(..) and getting and error. 我将两个值传递给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`

How can I convert Int32 to CGFloat to not return an error? 如何将Int32转换为CGFloat以不返回错误?

To convert between numerical data types create a new instance of the target type, passing the source value as parameter. 要在数值数据类型之间进行转换,请创建目标类型的新实例,并将源值作为参数传递。 So to convert an Int32 to a CGFloat : 所以要将Int32转换为CGFloat

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

In your case you can either do: 在您的情况下,您可以这样做:

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)

or: 要么:

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))

Note that there is no implicit or explicit type casting between numeric types in swift, so you have to use the same pattern also for converting a Int to Int32 or to UInt etc. 请注意,swift中的数值类型之间没有隐式或显式类型转换,因此您还必须使用相同的模式将Int转换为Int32或转换为UInt等。

只需使用CGFloat's初始化程序将widthheight显式转换为CGFloat

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM