Create a rectangle with just two rounded corners in swift?

后端 未结 15 2979
南笙
南笙 2020-11-28 03:14

I need to create a rectangle that have just two rounded corners in swift (Objective C code also ok).

At the moment my code is creating two rectangles with



        
15条回答
  •  春和景丽
    2020-11-28 03:42

    iOS 11+ Only | You can check iOS usage stats here

    Explanation

    Since the CACornerMask rawValue is an UInt you know that a CACornerMask rawValue is the sum of each CACornerMask.Element rawValue

    More specifically:

    • TopLeft (layerMinXMinYCorner) = 1
    • TopRight (layerMaxXMinYCorner) = 2
    • BottomLeft (layerMinXMaxYCorner) = 4
    • BottomRight (layerMaxXMaxYCorner) = 8

    So for example if you want top left and top right corners you can just type CACornerMask(rawValue: 3).


     Example

    Below a simple extension of an UIView

    extension UIView {
        enum Corner:Int {
            case bottomRight = 0,
            topRight,
            bottomLeft,
            topLeft
        }
        
        private func parseCorner(corner: Corner) -> CACornerMask.Element {
            let corners: [CACornerMask.Element] = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
            return corners[corner.rawValue]
        }
        
        private func createMask(corners: [Corner]) -> UInt {
            return corners.reduce(0, { (a, b) -> UInt in
                return a + parseCorner(corner: b).rawValue
            })
        }
        
        func roundCorners(corners: [Corner], amount: CGFloat = 5) {
            layer.cornerRadius = amount
            let maskedCorners: CACornerMask = CACornerMask(rawValue: createMask(corners: corners))
            layer.maskedCorners = maskedCorners
        }
    }
    

    You can use this like:

    let myRect = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
    myRect.roundCorners(corners: [.topRight, .topLeft])
    

提交回复
热议问题