Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing content scaleFactor / multiplier?

Tags:

ios

swift

view

I am working on an iPhone 6 Plus, and getting the bounds of my UIView using:

let viewBounds = view.bounds // GIVES 736 x 414 (Points), WHICH IS RIGHT

Is there any way that I can get the multiplier (i.e. the @3x) that is used to convert the points into pixels. I was hoping that I could use:

let scaleFactor = view.contentScaleFactor // GIVES 1

But as you can see it always seems to return 1. I know that I can grab the screen size directly using preferredMode.size or nativeBounds but I am sure there was a way before to access the multiplier too?

// WHERE SCALE FACTOR WOULD BE 3
let yRes = viewBounds.height * scaleFactor // 736 x 3 = 2208
let xRes = viewBounds.width * scaleFactor //  414 x 3 = 1242
like image 752
fuzzygoat Avatar asked Dec 25 '22 02:12

fuzzygoat


2 Answers

the UIView Class Reference documentation says about contentScaleFactor property:

(...) For system views, the value of this property may be 1.0 even on high resolution screens.

therefore that is not what you look for.


the actual scale factor can be read from the main screen, that will give you either 1.0, 2.0 or even 3.0:

let scale: CGFloat = UIScreen.main.scale // Swift3, Swift4.x
let scale: CGFloat = UIScreen.mainScreen().scale // Swift 2.x

or

CGFloat _scale = [[UIScreen mainScreen] scale]; // Obj-C

you can read more about the scale property in the UIScreen Class Reference.

like image 81
holex Avatar answered Dec 28 '22 07:12

holex


swift 3.0

let scale = UIScreen.main.scale
like image 22
Roman Andrykevych Avatar answered Dec 28 '22 07:12

Roman Andrykevych