Problem ze skalowaniem animacji CAShapeLayer [duplikat]

Nov 23 2020

Stworzyłem prostą ścieżkę do podpowiedzi suwaka. Chciałem, aby był animowany tak, jak się pojawia, aby użytkownik wiedział, że może go przeciągnąć.

Ale to nie animuje:

let upperToolTipPath: CAShapeLayer = CAShapeLayer()
            var path = UIBezierPath(roundedRect: CGRect(x: 0,y: 0, width: 65, height: 30), cornerRadius: 3)
            path.stroke()
            path.move(to: CGPoint(x: 50, y: 10))
            path.addLine(to: CGPoint(x: 40, y: 30))
            path.addLine(to: CGPoint(x: 15, y: 10))
            upperToolTipPath.path = path.cgPath
            self.layer.insertSublayer(upperToolTipPath, at: 0)
UIView.animate( 
                withDuration: 5,
                delay: 3,
                options: [.repeat, .autoreverse, .curveEaseIn],
                animations: {
                    self.upperToolTipPath.transform = CATransform3DMakeScale(2, 2, 1)
                    })

Czy możesz mi pomóc z animacją?

Odpowiedzi

3 matt Nov 23 2020 at 22:39

UIView.animatesłuży do animacji widoku . Ale upperToolTipPathjest warstwą ; nie jest to podstawowa warstwa widoku, więc można ją animować tylko za pomocą animacji warstwy . Oznacza to Core Animation, czyli CABasicAnimation.

Aby więc utworzyć animację, którą chcesz utworzyć, musisz użyć animacji podstawowej.

Alternatywnie możesz utworzyć widok, w którym znajduje się warstwa kształtu jako jej warstwa podstawowa. Wtedy możesz użyć animacji widoku.

Ale myślę, że w tym przypadku lepiej jest użyć Core Animation. Oto przykład tego, co myślę, że próbujesz zrobić:

let upperToolTipPath = CAShapeLayer()
upperToolTipPath.frame = CGRect(x: 0,y: 0, width: 65, height: 30)
let path = UIBezierPath(roundedRect: CGRect(x: 0,y: 0, width: 65, height: 30), 
    cornerRadius: 3)
upperToolTipPath.fillColor = UIColor.clear.cgColor
upperToolTipPath.strokeColor = UIColor.black.cgColor
upperToolTipPath.path = path.cgPath
self.layer.insertSublayer(upperToolTipPath, at: 0)
let b = CABasicAnimation(keyPath: #keyPath(CALayer.transform))
b.duration = 5
b.beginTime = CACurrentMediaTime() + 3
b.toValue = CATransform3DMakeScale(2, 2, 1)
b.repeatCount = .greatestFiniteMagnitude
b.autoreverses = true
upperToolTipPath.add(b, forKey:nil)