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
iOS 11+ Only | You can check iOS usage stats here
Since the CACornerMask
rawValue is an UInt
you know that a CACornerMask
rawValue is the sum of each CACornerMask.Element
rawValue
More specifically:
layerMinXMinYCorner
) = 1layerMaxXMinYCorner
) = 2layerMinXMaxYCorner
) = 4layerMaxXMaxYCorner
) = 8So for example if you want top left and top right corners you can just type CACornerMask(rawValue: 3)
.
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])