How can I have Half Oval UIButton
in Swift.
I want to have a button that has the shape of the grey area of the image
Note: the black background is not part of the button. The button is just the grey one.
I tried with
let circlePath = UIBezierPath.init(arcCenter: CGPoint(x: self.bounds.size.width / 2, y: bounds.size.height), radius: bounds.size.width / 2, startAngle: 0, endAngle: .pi, clockwise: true)
let circleShape = CAShapeLayer()
circleShape.path = circlePath.cgPath
self.layer.mask = circleShape
But I am getting semi-circle shape. Also I tried with changing the center and the radius of the arc still no chance.
CodePudding user response:
So it seems the problem really is merely drawing the shape shown in your drawing. If you can do that, you can use the shape however you like — for example, you can fill it and use the filled shape in a shape layer as a mask, and you already know how to do that. So let's concentrate on just the shape.
I was able to draw your shape like this:
I think that's a pretty fair approximation to what you've provided. Now I'll tell you how I drew it.
I assume the following relative dimensions (of course you can tweak these as desired): The vertical straight line on the right should be to the horizontal straight parts in the ratio 4:3.
For simplicity, then, I will just use dimensions of 40 (vertical) and 30 (horizontal straight), and I'll make my working space 50 points wide to allow room for the end-cap.
Here we go:
// assume proportions height 40, straight horizontal part 30
let path = CGMutablePath()
// start at the top right
path.move(to: .init(x: 50, y: 0))
// draw the top line
path.addLine(to: .init(x: 20, y: 0))
// add the arc
path.addRelativeArc(
center: .init(x: 20, y: 20),
radius: 20,
startAngle: -.pi/2,
delta: -.pi
)
// draw the bottom line
path.addLine(to: .init(x: 50, y: 40))
// finish
path.closeSubpath()
That's it! If you assign that path to a CAShapeLayer, you'll find that you get the shape in the picture above. Now you can simply adjust the parameters as desired and use the path in whatever way you like.