カテゴリー
iOS Swift

CAShapeLayerをアニメーションさせる

CAShapeLayerのpositionをfor loop内でインクリメントし、アニメーションさせてみます。

import UIKit

class ViewController: UIViewController {
    
    var dotShapeLayer = CAShapeLayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        showPoint()
        movePoint()
    }

    func showPoint() {
        view.layer.addSublayer(dotShapeLayer)
        let dotRect = CGRect(x: 0, y: 0, width: 10, height: 10)
        let smallDotPath = UIBezierPath(rect: dotRect)
        dotShapeLayer.path = smallDotPath.cgPath
    }
    
    func movePoint() {
        DispatchQueue.global().async {
            for i in 0...100 {
                DispatchQueue.main.async {
                    self.dotShapeLayer.position = CGPoint(x: i * 2, y: i * 2)
                    self.view.layer.setNeedsDisplay()
                }
                sleep(1)
            }
        }
    }
}