Search code examples
swiftgeometryautolayoutuibezierpath

How To Make a Quarter Circle using AutoLayout


How can I make a quadrant (quarter-circle) like the one below, using Auto-Layout in Swift? I understand that UIBezierPath is required but I can't seem to get it to work.

enter image description here


Solution

  • Quick, simple example:

    class QuarterCircleView: UIView {
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            // only add the shape layer once
            if layer.sublayers == nil {
                let lay = CAShapeLayer()
                lay.fillColor = UIColor.blue.cgColor
                layer.addSublayer(lay)
            }
            if let lay = layer.sublayers?.first as? CAShapeLayer {
                let center = CGPoint(x: bounds.midX, y: bounds.midY)
                let bez  = UIBezierPath()
                bez.move(to: center)
                bez.addArc(withCenter: center, radius: bounds.width * 0.5, startAngle: .pi, endAngle: .pi * 1.5, clockwise: true)
                bez.close()
                lay.path = bez.cgPath
            }
        }
        
    }
    

    Note: you really should show what you've tried when posting a question. Search for CAShapeLayer and read some tutorials.