Skip to content

Instantly share code, notes, and snippets.

@calvingit
Last active November 4, 2023 11:38
Show Gist options
  • Save calvingit/ac777ad92fc3d096195b4bbb22361fd6 to your computer and use it in GitHub Desktop.
Save calvingit/ac777ad92fc3d096195b4bbb22361fd6 to your computer and use it in GitHub Desktop.
// iOS 11 之后的方法,来自: https: // www.appcoda.com/rounded-corners-uiview/
// layerMaxXMaxYCorner – lower right corner
// layerMaxXMinYCorner – top right corner
// layerMinXMaxYCorner – lower left corner
// layerMinXMinYCorner – top left corner
func roundCorners(cornerRadius: Double) {
self.layer.cornerRadius = CGFloat(cornerRadius)
self.clipsToBounds = true
self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
}
// iOS 11 之前的方法
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
// Use it like this
view.roundCorners(corners: [.topLeft, .topRight], radius: 20)
// 注意:当 View 改变大小的时候,mask 不会变化,需要手动改变
class View: UIView {
override func layoutSubviews() {
super.layoutSubviews()
roundCorners(corners: [.topLeft, .topRight], radius: 20)
}
}
class ViewController: UIViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
yourView.roundCorners(corners: [.topLeft, .topRight], radius: 20)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment