Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a semi-circle button iOS

Tags:

ios

swift

I am trying to draw a semi-circle button. I'm having trouble both drawing the semi-circle and attaching it to the button I made in xcode. The button in xcode has constraints pinning it to the bottom of the screen and centering it. I reference the button in my view controller and then try to override it to a semi-circle as follows. I am getting a blank button. I also hard coded in the coordinates from the storyboard of where the button is. Is there a better way to do that?

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
like image 714
garrettmaring Avatar asked Oct 23 '15 18:10

garrettmaring


1 Answers

The problem is that your shape layer is positioned way outside the buttons bounds. If you just add the shape layer as a subview of your button's layer you'll see the problem:

button.layer.addSublayer(circleShape)

enter image description here

You have to adjust the arc center point, so that the arc lies within the button's bounds:

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'll get this:

enter image description here

like image 195
joern Avatar answered Nov 16 '22 02:11

joern