以Swift为整数获取屏幕大小

时间:2015-05-12 11:11:55

标签: ios swift

为了在屏幕中随机定位元素但在边界内,我需要快速分辨率/屏幕尺寸。我已经知道如何使用CGGraphics获得它。不幸的是,我需要计算一下,需要将其作为UInt32类型,而不是CGFloat。我不能用那种方式进行铸造。有什么想法吗?

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
//What I want to do
let screenHeight = screenSize.height-arc4random_uniform(screenSize.height)

4 个答案:

答案 0 :(得分:15)

如果您想要元素的随机X和Y位置,您可以执行以下操作:

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat(arc4random_uniform(UInt32(screenSize.width)))
let randomYPos = CGFloat(arc4random_uniform(UInt32(screenSize.height)))

Swift 4.2

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat.random(in: 0..<screenSize.width)
let randomYPos = CGFloat.random(in: 0..<screenSize.height)

答案 1 :(得分:3)

要在Int中直接获取值,请使用此代码

var bounds: CGRect = UIScreen.mainScreen().bounds
    var w:Int  = Int(self.bounds.size.width)
    var h:Int  = Int(self.bounds.size.height)

您所要做的就是将返回值从CGFloat转换为Integer

使用以下代码获取屏幕高度宽度的值,然后将CGFloat转换为Int

var bounds: CGRect = UIScreen.mainScreen().bounds
var width:CGFloat = bounds.size.width
var height:CGFloat = bounds.size.height

答案 2 :(得分:2)

你试试这个

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let screenWidth = screenSize.width * 0.75

答案 3 :(得分:1)

我认为这就是你所需要的:

let screenHeight = screenSize.height - CGFloat(arc4random_uniform(UInt32(screenSize.height)))