Skip to content

Instantly share code, notes, and snippets.

@shaildyp
Last active December 7, 2022 12:14
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save shaildyp/6cd1de39498ff7b3c22fa758f005f7cd to your computer and use it in GitHub Desktop.
Save shaildyp/6cd1de39498ff7b3c22fa758f005f7cd to your computer and use it in GitHub Desktop.
Backward compatible maskedCorners of iOS 11.
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
}
}
}
@zahariadaniel16
Copy link

Man, this is gold. Just thank you.

@yildirimatcioglu
Copy link

saved my day thanks

@egzonpllana
Copy link

Great coding!

Example all four corners with radius:
self.tabBar.maskedCorners([.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner], radius: tabBarHeight/2)

@Deadpikle
Copy link

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 an NSBezierPath, nor can you natively create an NSBezierPath with specific corners rounded. To make an NSBezierPath with specific rounded corners, use the NSBezierPath code you can get from here (MIT licensed) with whatever adjustments you need for your codebase. Then translate it to a CGPath using the code from here. Then, just like the gist, do:

caLayer.path = cgPath
self.layer.mask = caShapeLayer

@wangdu1005
Copy link

Thanks my god.

@wsnjy
Copy link

wsnjy commented May 14, 2020

dude, this is awesome. Thanks for the code!

@shailesh-bbc
Copy link

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