Skip to content

Instantly share code, notes, and snippets.

@jeffaburt
Last active December 31, 2023 12:32
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffaburt/68fdee211b9f9061fbffc28819b5e540 to your computer and use it in GitHub Desktop.
Save jeffaburt/68fdee211b9f9061fbffc28819b5e540 to your computer and use it in GitHub Desktop.
Converts pixels to points based on the screen scale
import UIKit
public extension CGFloat {
/**
Converts pixels to points based on the screen scale. For example, if you
call CGFloat(1).pixelsToPoints() on an @2x device, this method will return
0.5.
- parameter pixels: to be converted into points
- returns: a points representation of the pixels
*/
func pixelsToPoints() -> CGFloat {
return self / UIScreen.main.scale
}
/**
Returns the number of points needed to make a 1 pixel line, based on the
scale of the device's screen.
- returns: the number of points needed to make a 1 pixel line
*/
static func onePixelInPoints() -> CGFloat {
return CGFloat(1).pixelsToPoints()
}
}
@MaTriXy
Copy link

MaTriXy commented May 11, 2020

update
func pixelsToPoints() -> CGFloat { return self / UIScreen.main.scale }

@jeffaburt
Copy link
Author

Thanks! I've updated the original gist with your suggestion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment