Skip to content

Instantly share code, notes, and snippets.

@shaildyp
Last active December 7, 2022 12:14
Show Gist options
  • Select an option

  • Save shaildyp/6cd1de39498ff7b3c22fa758f005f7cd to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Man, this is gold. Just thank you.

@yildirimatcioglu
Copy link
Copy Markdown

saved my day thanks

@egzonpllana
Copy link
Copy Markdown

Great coding!

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

@Deadpikle
Copy link
Copy Markdown

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
Copy Markdown

Thanks my god.

@wsnjy
Copy link
Copy Markdown

wsnjy commented May 14, 2020

dude, this is awesome. Thanks for the code!

@shailesh-bbc
Copy link
Copy Markdown

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