Draw a semi-circular iOS button
I am trying to draw a semi-circular button. I am having trouble showing a semicircle and attaching it to a button that I made in xcode. A button in xcode has constraints fixing it to the bottom of the screen and centering it. I am accessing a button in a view controller and then trying to redefine it to a semicircle like this. I am getting an empty button. I also hardcoded the coordinates from the storyboard where the button is. Is there a better way to do this?
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: 113.0, y: 434.0),
radius: 10.0, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.CGPath
sunButton.layer.mask = circleShape
source to share
The problem is that your form layer is outside the borders of the buttons. If you just add a shape layer as a subzone of your button layer, you will see a problem:
button.layer.addSublayer(circleShape)
You have to adjust the center point of the arc so that the arc is inside the button border:
let circlePath = UIBezierPath.init(arcCenter: CGPointMake(button.bounds.size.width / 2, 0), radius: button.bounds.size.height, startAngle: 0.0, endAngle: CGFloat(M_PI), clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.CGPath
button.layer.mask = circleShape
And you get this:
source to share
Swift 5 update:
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: button.bounds.size.width / 2, y: 0), radius: button.bounds.size.height, startAngle: 0.0, endAngle: .pi, clockwise: true) let circleShape = CAShapeLayer() circleShape.path = circlePath.cgPath button.layer.mask = circleShape
source to share