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.
}
}