Ho realizzato una semplice animazione UIBezierPath
con Swift. Questo percorso consiste nella creazione di un rettangolo arrotondato con un bordo colorato. L'animazione deve essere il disegno del bordo colorato. Per fare ciò, ho creato un CAShapeLayer
con un UIBezierPath(roundedRect:, cornerRadius:)
Swift: UIBezierPath Stroke Animation from Center
let layer = CAShapeLayer()
var viewPrueba = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
viewPrueba = UIView(frame: CGRectMake(self.view.frame.width/2-100, self.view.frame.height/2 - 100, 200, 200))
self.view.addSubview(viewPrueba)
let path = UIBezierPath(roundedRect: CGRectMake(0, 0, 200, 200), cornerRadius: 40.0)
layer.path = path.CGPath
layer.fillColor = UIColor.clearColor().CGColor
layer.strokeColor = UIColor.blueColor().CGColor
layer.strokeStart = 0.0
layer.strokeEnd = 0.0
layer.lineWidth = 4.0
layer.lineJoin = kCALineJoinRound
viewPrueba.layer.addSublayer(layer)
let tapGR = UITapGestureRecognizer(target: self, action: #selector(ViewController.anim))
self.view.addGestureRecognizer(tapGR)
}
func anim() {
let anim1 = CABasicAnimation(keyPath: "strokeEnd")
anim1.fromValue = 0.0
anim1.toValue = 1.0
anim1.duration = 4.0
anim1.repeatCount = 0
anim1.autoreverses = false
anim1.removedOnCompletion = false
anim1.additive = true
anim1.fillMode = kCAFillModeForwards
self.layer.addAnimation(anim1, forKey: "strokeEnd")
}`
Funziona bene. L'unico problema è che l'animazione inizia dalla parte in alto a sinistra del quadrato e non dal centro in alto. Come lo posso fare?
L'unica cosa che ho trovato al fine di ottenere questo è farlo con un cerchio e non un rettangolo, che non è quello che vogliamo.
Grazie
Funziona come un incantesimo! Grazie! :) – rulilg