CABasicAnimation不围绕中心缩放

时间:2017-03-14 13:25:59

标签: ios iphone swift core-animation cabasicanimation

我想同时执行不透明度和缩放效果我的动画完美但它的位置不合适。我想在中心执行动画。 这是我的代码。

    btn.backgroundColor = UIColor.yellowColor()
    let stroke =  UIColor(red:236.0/255, green:0.0/255, blue:140.0/255, alpha:0.8)
    let pathFrame = CGRectMake(24, 13, btn.bounds.size.height/2, btn.bounds.size.height/2)

    let circleShape1 = CAShapeLayer()
    circleShape1.path = UIBezierPath(roundedRect: pathFrame, cornerRadius: btn.bounds.size.height/2).CGPath
    circleShape1.position = CGPoint(x: 2, y: 2)
    circleShape1.fillColor = stroke.CGColor
    circleShape1.opacity = 0

    btn.layer.addSublayer(circleShape1)

    circleShape1.anchorPoint = CGPoint(x: 0.5, y: 0.5)

    let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
    scaleAnimation.fromValue = NSValue(CATransform3D: CATransform3DIdentity)
    scaleAnimation.toValue = NSValue(CATransform3D: CATransform3DMakeScale(2.0, 2.0, 1))

    let alphaAnimation = CABasicAnimation(keyPath: "opacity")
    alphaAnimation.fromValue = 1
    alphaAnimation.toValue = 0

    CATransaction.begin()
    let animation = CAAnimationGroup()
    animation.animations = [scaleAnimation, alphaAnimation]
    animation.duration = 1.5
    animation.repeatCount = .infinity
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
    circleShape1.addAnimation(animation, forKey:"Ripple")
    CATransaction.commit()

enter image description here

3 个答案:

答案 0 :(得分:3)

问题是你没有正确地对抗框架。你说:

 let circleShape1 = CAShapeLayer()

但你忘了给circleShape1一个框架!因此,它的大小为零,当你为它设置动画时会发生非常奇怪的事情。你在下一行的工作应该是分配circleShape1一个框架。例如:

circleShape1.frame = pathFrame

那可能是也可能不是正确的框架;它可能不是。但你需要明白这一点。

然后,您需要根据形状图层界限来修复Bezier路径的框架:

circleShape1.path = UIBezierPath(roundedRect: circleShape1.bounds // ...

答案 1 :(得分:0)

您需要创建{0,0}位置的路径框架,并将正确的框架设置为图层:

let pathFrame = CGRectMake(0, 0, btn.bounds.size.height/2, btn.bounds.size.height/2)
....
circleShape1.frame = CGRect(x: 0, y: 0, width: pathFrame.width, height: pathFrame.height)
circleShape1.position = CGPoint(x: 2, y: 2)

如果要创建{13,24}位置的路径,则需要更改图层中的宽度和高度。你的形状应该在图层的中心。

答案 2 :(得分:0)

我从未使用子图层,因此我会使用子视图来制作它,使代码更容易:

btn.backgroundColor = UIColor.yellow

let circleShape1 = UIView()

circleShape1.frame.size = CGSize(width: btn.frame.height / 2, height: btn.frame.height / 2)
circleShape1.center = CGPoint(x: btn.frame.width / 2, y: btn.frame.height / 2)
circleShape1.layer.cornerRadius = btn.frame.height / 4
circleShape1.backgroundColor = UIColor(red:236.0/255, green:0.0/255, blue:140.0/255, alpha:0.8)
circleShape1.alpha = 1

btn.addSubview(circleShape1)

UIView.animate(withDuration: 1,
               delay: 0,
               options: [.repeat, .curveLinear],
               animations: {
                    circleShape1.transform = CGAffineTransform(scaleX: 5, y: 5)
                    circleShape1.alpha = 0.4
               }, completion: nil)