I am trying to set cornerRadius of UIButton but I dont know how to do it.
If I do like this:
button.layer.cornerRadius = 5;
works w
Using UIGraphicsImageRenderer
, you can use the cgContext
property of UIGraphicsImageRendererContext
to access the CGContext
and add a rounded path:
UIGraphicsImageRenderer(size: size).image { context in
let rect = CGRect(origin: .zero, size: size)
let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
context.cgContext.addPath(clipPath)
context.cgContext.setFillColor(self.cgColor)
context.cgContext.fillPath()
}
Added as an extension to UIColor
:
extension UIColor {
public func image(_ size: CGSize = CGSize(width: 10, height: 10), cornerRadius: CGFloat = 4) -> UIImage {
return UIGraphicsImageRenderer(size: size).image { context in
let rect = CGRect(origin: .zero, size: size)
let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
context.cgContext.addPath(clipPath)
context.cgContext.setFillColor(self.cgColor)
context.cgContext.fillPath()
}
}
}
This approach will also allow you to add a shadow to the button unlike using clipsToBounds
.