缩放CAShapeLayer的动画时出现问题


我为滑块的工具提示创建了一个简单的路径。我想让它看起来像动画一样,这样用户就会知道他可以拖动它

但它没有动画:

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

你能帮我做动画吗?

UIView.animate用于视图动画。但upperToolTipPath;它不是视图的主要层,因此只能使用动画对其进行动画设置。这意味着核心动画,即CABasicAnimation。

因此,要制作您想要制作的动画,您需要使用核心动画。

或者,可以创建一个视图,将图形层作为其主要层。然后就可以使用视图动画了。

但我认为在这种情况下最好使用核心动画。以下是我认为你正在尝试做的事情的例子:

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)

最新更新