Swift CAShapeLayer 和 貝塞爾曲線 實現圓環進度條動畫,顯示圓形轉化成矩形


 

 

 

import UIKit

 

class ViewController: UIViewController {

    var timer :Timer!

    var shapeLayer:CAShapeLayer!

    override func viewDidLoad() {

        super.viewDidLoad()

        

        CircleAnimate()

        rectTransToCircle()

    }

    

    //圓形進度條動畫

    func CircleAnimate(){

        shapeLayer = CAShapeLayer()

        self.view.layer.addSublayer(shapeLayer)

        //使用貝塞爾曲線畫一個圓形

        let onePath = UIBezierPath(arcCenter: CGPoint(x:300,y:150), radius: 100, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true)

        //CAShapeLayer 的路徑

        shapeLayer.path = onePath.cgPath

        //描線的線寬

        shapeLayer.lineWidth = 30

        //描線起始點

        shapeLayer.strokeStart = 0

        //描線終點

        shapeLayer.strokeEnd = 0

        //填充色

        shapeLayer.fillColor = UIColor.clear.cgColor

        timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(animate), userInfo: nil, repeats: true)

    }

    //定時器

    @objc func animate(){

        shapeLayer.strokeColor = UIColor.blue.cgColor

        if  shapeLayer.strokeEnd < 1{

            self.shapeLayer.strokeEnd += 0.2

        }else{

            timer.invalidate()

        }

    }

    

    //矩形轉換成圓形

    func rectTransToCircle(){

        let secondShapeLayer = CAShapeLayer()

        self.view.layer.addSublayer(secondShapeLayer)

        let circlePath = UIBezierPath(arcCenter: CGPoint(x:200,y:500), radius: 200, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: true)

        //使用貝塞爾曲線畫一個矩形

        let rectPath = UIBezierPath()

        rectPath.move(to: CGPoint(x: 100, y: 100))

        rectPath.addLine(to: CGPoint(x: 100, y: 150))

        rectPath.addLine(to: CGPoint(x: 150, y: 150))

        rectPath.addLine(to: CGPoint(x: 150, y: 100))

        rectPath.addLine(to: CGPoint(x: 100, y: 100))

 

        //添加路徑動畫

        let basicAnimate = CABasicAnimation(keyPath: "path")

        basicAnimate.fromValue = circlePath.cgPath

        basicAnimate.toValue = rectPath.cgPath

        basicAnimate.duration = 2

        basicAnimate.repeatCount = 1

        basicAnimate.isRemovedOnCompletion = false

        //CAShapeLayer添加動畫

        secondShapeLayer.path = rectPath.cgPath

        secondShapeLayer.add(basicAnimate, forKey: "shape")

    }

    

    

 

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

 

 

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM