Search code examples
swiftdrawshapes

Drawing shapes with constraints swift 4


i'm trying to learn how to draw shapes and animate it, i succeeded at both and i managed to draw shapes in the center of my screen and in alignment to each other, but when i change my simulator to any device other than my view as device they jump out of the center of the screen, is there any way to set constraints to my drawn shapes so that they are always in the center?

here is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.



    // rect


    let layer = CAShapeLayer()
    let bounds = CGRect(x: 60, y: 200, width: 250, height: 250)
    layer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 20, height: 20)).cgPath
    layer.strokeColor = UIColor.white.cgColor
    layer.fillColor = UIColor.clear.cgColor
    layer.lineWidth = 4

    view.layer.addSublayer(layer)


    let rectAnimation = CABasicAnimation(keyPath: "strokeEnd")
    rectAnimation.fromValue = 0
    rectAnimation.toValue = 1
    rectAnimation.duration = 2


    layer.add(rectAnimation, forKey: "line")



}

Solution

  • A powerful tool to give constraint is Masonry, you will really appreciate it. It's super easy for setting constraints and for animating them; Else you can set your x and y "bounds" coordinates to be at centerX and centerY too