Edoardo
Edoardo

Reputation: 675

Wrong position of Circle of CircleView in view

I have a custom view that draws a circle. I set up my custom view with aspect ratio 1:1 and equal height of 0.5 multiplier to the main view. My problem is that my circle doesn't set in the center of the view.

enter image description here

My set up: enter image description here

The code of CirlceView:

class CircleProgress: UIView {
private var trackLayer = CAShapeLayer()
override func awakeFromNib() {
    super.awakeFromNib()
    setupTrackLayer()
}

func setupTrackLayer() {
    let centerPoint = CGPoint(x: bounds.width/2 , y: bounds.height/2)


    let circularPath = UIBezierPath(arcCenter: centerPoint, radius: frame.width/2, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
    trackLayer.lineWidth = 20
    trackLayer.path = circularPath.cgPath
    trackLayer.strokeColor = #colorLiteral(red: 1, green: 0.9450980392, blue: 0.462745098, alpha: 1).cgColor
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = kCALineCapRound
    layer.addSublayer(trackLayer)
}

}

Upvotes: 0

Views: 64

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Edit: see demo here CircleView

var Once:Bool = true

override func layoutSubviews()
{
   if(Once)
   {
      setupTrackLayer()
      Once = false
   }

}

Or put code in draw(_ Rect

Edit: try this , the problem is using frame , use bounds which is relative to screen

   func drawTimeLeftShape() {
    timeLeftShapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: self.bounds.size.width / 2.0 , y:  self.bounds.size.height / 2.0), radius:
        min(self.bounds.size.width/2, self.bounds.size.height/2), startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true).cgPath
    timeLeftShapeLayer.strokeColor = UIColor.red.cgColor
    timeLeftShapeLayer.fillColor = UIColor.clear.cgColor
    timeLeftShapeLayer.lineWidth = 15
    self.layer.addSublayer(timeLeftShapeLayer)
}

Upvotes: 1

Related Questions