Search code examples
iosswiftswift4uibezierpathcurve

I want design bunch of circles connecting with curved lines


Want to achieve something like this I have created circle using UIView but during creating quadCurve unable to find the control point for each line

func drawLineFromPoint(point1:CGPoint, point2:CGPoint) {
    let path = UIBezierPath()
    path.move(to: point1)
   // path.addLine(to: point2)
   path.flatness = 0.9
    path.addQuadCurve(to: point2, controlPoint: CGPoint(x: (point1.x+point2.x), y: (point1.y)))


let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 5
shapeLayer.fillColor = UIColor.clear.cgColor

self.centerView.layer.addSublayer(shapeLayer)

Solution

  • You don't need to draw each of the lines between the small circles. You can draw big circle first, then draw small circles on that big circle.

    For example:

    override func draw(_ rect: CGRect) {
        // change these as you wish
        let colors = [UIColor.red, .blue, .green, .red, .blue, .green, .red, .blue, .green, .red, .blue, .green]
        let bigCircleRect = self.bounds.insetBy(dx: 16, dy: 16) // This is how big the big circle is compared to the view
        let bigCircle = UIBezierPath(ovalIn: bigCircleRect)
        bigCircle.lineWidth = 5
        UIColor.black.setStroke() // color of the big circle
        bigCircle.stroke()
    
        for (index, angle) in stride(from: -CGFloat.pi, to: .pi - .pi / 6, by: .pi / 6).enumerated() {
            let centerOfCircle = CGPoint(x: (bigCircleRect.width / 2) * cos(angle) + bounds.width / 2,
                                         y: (bigCircleRect.width / 2) * sin(angle) + bounds.width / 2)
            let smallCircleRect = CGRect(origin: centerOfCircle, size: .zero).insetBy(dx: -16, dy: -16) // size of small circle
            let smallCircle = UIBezierPath(ovalIn: smallCircleRect)
            colors[index].setFill()
            smallCircle.fill()
    
        }
    }
    

    Output:

    enter image description here