-
-
Save shaildyp/6cd1de39498ff7b3c22fa758f005f7cd to your computer and use it in GitHub Desktop.
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 | |
} | |
} | |
} |
saved my day thanks
Great coding!
Example all four corners with radius:
self.tabBar.maskedCorners([.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner], radius: tabBarHeight/2)
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
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.
Man, this is gold. Just thank you.