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

      

+3


source to share


2 answers


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)

      

enter image description here

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:

enter image description here

+10


source


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

      

0


source







All Articles