Last active
December 7, 2022 12:14
-
-
Save shaildyp/6cd1de39498ff7b3c22fa758f005f7cd to your computer and use it in GitHub Desktop.
Backward compatible maskedCorners of iOS 11.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIView { | |
func roundCorners(_ corners: CACornerMask, radius: CGFloat) { | |
if #available(iOS 11, *) { | |
self.layer.cornerRadius = radius | |
self.layer.maskedCorners = corners | |
} else { | |
var cornerMask = UIRectCorner() | |
if(corners.contains(.layerMinXMinYCorner)){ | |
cornerMask.insert(.topLeft) | |
} | |
if(corners.contains(.layerMaxXMinYCorner)){ | |
cornerMask.insert(.topRight) | |
} | |
if(corners.contains(.layerMinXMaxYCorner)){ | |
cornerMask.insert(.bottomLeft) | |
} | |
if(corners.contains(.layerMaxXMaxYCorner)){ | |
cornerMask.insert(.bottomRight) | |
} | |
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: cornerMask, cornerRadii: CGSize(width: radius, height: radius)) | |
let mask = CAShapeLayer() | |
mask.path = path.cgPath | |
self.layer.mask = mask | |
} | |
} | |
} |
Thanks my god.
dude, this is awesome. Thanks for the code!
I don't even remember this code anymore. Glad that it is still useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you happen to get here and are on macOS, the fallback doesn't work as the APIs are a little different and you can't grab a
CGPath
straight from anNSBezierPath
, nor can you natively create anNSBezierPath
with specific corners rounded. To make anNSBezierPath
with specific rounded corners, use theNSBezierPath
code you can get from here (MIT licensed) with whatever adjustments you need for your codebase. Then translate it to aCGPath
using the code from here. Then, just like the gist, do: