Setting a UIView
's corner radius can be done the following ways:
Set the
layer
'scornerRadius
property:view.layer.cornerRadius = 5; view.layer.masksToBounds = true;
Apply a mask:
func roundCorners(corners:UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask }
Override
draw(_:)
:func draw(_ rect: CGRect) { // Size of rounded rectangle let rectWidth = rect.width let rectHeight = rect.height // Find center of actual frame to set rectangle in middle let xf: CGFloat = (self.frame.width - rectWidth) / 2 let yf: CGFloat = (self.frame.height - rectHeight) / 2 let ctx = UIGraphicsGetCurrentContext()! ctx.saveGState() let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight) let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath ctx.addPath(clipPath) ctx.setFillColor(rectBgColor.cgColor) ctx.closePath() ctx.fillPath() ctx.restoreGState() }
Which of these is generally considered to be the "correct" way of implementing rounded corners on a UIView
, accounting for the following criteria:
- configuration (some corners may be rounded while others are not)
- animation (can you animate the
cornerRadius
changing) - flexibility (does it break third party libraries or masks you have already applied)
- readability (how concise/reusable is the solution)
- speed (does it negatively impact performance)