CABasicAnimation 圈 CAShapeLayer 在地图上移动而不是缩放

CABasicAnimation circle CAShapeLayer moving across the map instead of scaling

我正在尝试创建隐藏视图的动画。起初它从屏幕上的一个点开始(例如 150)并按比例放大直到它适合整个屏幕。这是我试过的

public func testAnimation(anchor : CGRect){
    self.isHidden = false
    let mask = CAShapeLayer()
    let radius = 15
    mask.path = UIBezierPath(roundedRect: CGRect(x: 150,y: 150, width:  Double(radius), height: Double(radius)), cornerRadius: CGFloat(radius/2)).cgPath
    mask.position = CGPoint(x: 150,y: 150 )
    mask.fillColor = UIColor.blue.cgColor

    self.layer.mask = mask
    let oldBounds = mask.bounds
    let newBounds = CGRect.init(x: 150,y: 150,width: 1600,height: 1600)
    let revealAnimation = CABasicAnimation(keyPath: "bounds")
    revealAnimation.fromValue = NSValue(cgRect: oldBounds)
    revealAnimation.toValue = NSValue(cgRect: newBounds)
    revealAnimation.duration = 5

    //Keep the bounds after the animation completes.
    mask.bounds = newBounds
    mask.add(revealAnimation, forKey: "revealAnimation")
}

此代码段的问题在于它会导致一个小圆圈在屏幕中移动,而不是使圆圈变大。我使用了此处找到的代码:http://blog.ericd.net/2015/10/22/swift-animating-a-mask-for-a-uiview/(showUnderView 函数),它的效果非常好。我将 CALayer 换成 CAShapeLayer 以获得圆形效果,但它不起作用。

动画 CALayer 的边界本来可以工作,但这里您使用的是 CAShapeLayer。设置新边界不会重绘和缩放形状。

相反,您应该尝试直接为形状制作动画:

let finalRadius: CGFloat = 1600
let finalPath = UIBezierpath(roundedRect: CGRect(x: 150, y: 150, width: finalRadius, height: finalRadius), cornerRadius: finalRadius / 2).cgPath

let revealAnimation = CABasicAnimation(keyPath: "path")
revealAnimation.toValue = finalPath
revealAnimation.duration = 5
mask.add(revealAnimation, forKey: "revealAnimation")

这将以所需的大小重新绘制形状。

如果你想保持形状居中,你可以同时设置 position 的动画。