Search code examples
iosswiftcore-graphicsuibezierpath

How to draw a custom rounded rectangle in SWIFT?


I'm trying to draw this shape

setting cornerRadius doesn't work

I'm trying to draw a shape shown on the upper image programmatically.

This shape has custom rounded corners.

view.layer.cornerRadius = some value less than half diameter

This didn't work. Setting cornerRadius draws straight lines on every side(as seen on the bottom image) but the shape I'm trying to draw has no straight lines at all and it's not an oval.

I also tried below without luck. This code just draws an oval.

var path = UIBezierPath(ovalIn: CGRect(x: 000, y: 000, width: 000, height: 000))

I believe this can not be done by setting cornerRadius.

There should be something more.

I have no idea what class should I use and how.

Please anybody give me some direction.

Thanks!


Solution

  • I accomplished this by drawing a quadratic.

    let dimention: CGFloat = some value
    
    let path = UIBezierPath()
        path.move(to: CGPoint(x: dimension/2, y: 0))
        path.addQuadCurve(to: CGPoint(x: dimension, y: dimension/2),
                          controlPoint: CGPoint(x: dimension, y: 0))
        path.addQuadCurve(to: CGPoint(x: dimension/2, y: dimension),
                          controlPoint: CGPoint(x: dimension, y: dimension))
        path.addQuadCurve(to: CGPoint(x: 0, y: dimension/2),
                          controlPoint: CGPoint(x: 0, y: dimension))
        path.addQuadCurve(to: CGPoint(x: dimension/2, y: 0),
                          controlPoint: CGPoint(x: 0, y: 0))
        path.close()
    
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = path.cgPath
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.position = CGPoint(x: 0, y: 0)
    
        self.someView.layer.addSublayer(shapeLayer)