Search code examples
iosswiftuiviewdrawinguibezierpath

Swift Draw multiple circles in order


How to draw multiple circles in order in Swift, When the user enters a number in the TextField I want to draw the quantity in circles in the View on the Left:

Sample: enter image description here

So far this is my code:

func drawCircleInsideView(view: UIView, count: Int){
    let halfSize:CGFloat = min(view.bounds.size.width/2, view.bounds.size.height/2) / CGFloat(count)
    let desiredLineWidth:CGFloat = 1
    var i = 0
    var lastPosition = 0
    while i <= count {
      print(“THIAGO: “, i)
      i = i + 1
      let circlePath = UIBezierPath(
          arcCenter: CGPoint(x:halfSize,y:halfSize),
          radius: CGFloat( halfSize - (desiredLineWidth/2) ),
          startAngle: CGFloat(0),
          endAngle:CGFloat(Double.pi * 2),
          clockwise: true)
      let shapeLayer = CAShapeLayer()
      shapeLayer.path = circlePath.cgPath
      shapeLayer.fillColor = UIColor.green.cgColor
      shapeLayer.strokeColor = UIColor.green.cgColor
      shapeLayer.lineWidth = desiredLineWidth
      view.layer.addSublayer(shapeLayer)
      lastPosition = lastPosition + 2
    }
  }

Solution

  • You need to use i .. to change centre of your circle

    func drawCircleInsideView(view: UIView, count: Int){
          let halfSize:CGFloat = min(view.bounds.size.width/2, view.bounds.size.height/2) / CGFloat(count)
          let desiredLineWidth:CGFloat = 1
          var i = 0
          var lastPosition = 0
          while i <= count {
            print("THIAGO: ", i)
            i = i + 1
            let circlePath = UIBezierPath(
                arcCenter: CGPoint(x:halfSize,y:halfSize + (CGFloat(i) * halfSize*2)),
                radius: CGFloat( halfSize - (desiredLineWidth/2) ),
                startAngle: CGFloat(0),
                endAngle:CGFloat(Double.pi * 2),
                clockwise: true)
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = circlePath.cgPath
            shapeLayer.fillColor = UIColor.green.cgColor
            shapeLayer.strokeColor = UIColor.green.cgColor
            shapeLayer.lineWidth = desiredLineWidth
            view.layer.addSublayer(shapeLayer)
            lastPosition = lastPosition + 2
          }
        }
    

    Result

    enter image description here