포스트

How to round corners specifically on a UIView

KOR

To round a corner on a UIView, you can set the layer’s cornerRadius value. Simply use it like this:

1
cornerView.layer.cornerRadius = 8

To ensures subviews are clipped to the rounded corners, add ‘view.clipsToBounds = true’.

But what if you need to corner only to top view or bottom? We need to set the CALayer’s maskedCorners property. You can make an extension for making a rounded corner like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
extension UIView {
    // Available from iOS 11.0
    func cornerRadius(_ corners: UIRectCorner..., radius: CGFloat) {
        layer.cornerRadius = radius
        
        var maskedCorners: CACornerMask = []
        let cornerSet = corners.isEmpty ? [.allCorners] : corners
        
        if cornerSet.contains(.allCorners) {
            maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner]
        } else {
            if cornerSet.contains(.topLeft) {
                maskedCorners.insert(.layerMinXMinYCorner)
            }
            if cornerSet.contains(.topRight) {
                maskedCorners.insert(.layerMaxXMinYCorner)
            }
            if cornerSet.contains(.bottomLeft) {
                maskedCorners.insert(.layerMinXMaxYCorner)
            }
            if cornerSet.contains(.bottomRight) {
                maskedCorners.insert(.layerMaxXMaxYCorner)
            }
        }
        
        layer.maskedCorners = maskedCorners
    }
}

This extension provides the following features

  • Multiple corners can be set at once using variable parameters.
  • The mapping between UIRectCorner and CACornerMask makes it easy to set the desired corners
  • Combine all selected corners into one mask using the reduce function

The below table show mapping between CACornerMask and corner.

CACornerMaskCorner
layerMinXMinYCornertop left corner
layerMaxXMinYCornertop right corner
layerMinXMaxYCornerbottom left corner
layerMaxXMaxYCornerbottom right corner

// Usage

1
2
3
4
5
6
7
8
9
10
11
// All corners rounded
circleView.cornerRadius(.allCorners, radius: 50)

// Only top corners rounded
circleView.cornerRadius(.topLeft, .topRight, radius: 50)

// Only left corners rounded
circleView.cornerRadius(.topLeft, .bottomLeft, radius: 25)

// Only diagonal corners rounded
circleView.cornerRadius(.topLeft, .bottomRight, radius: 25)


Related Resources
cornerRadius

maskedCorners

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.