Skip to content

Instantly share code, notes, and snippets.

@jeffaburt
Last active August 2, 2024 18:53
Show Gist options
  • 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()
}
}
@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