Reputation: 3016
I have one view in which need to add one layer. I successfully added the layer but now i want to do animation for it's width means layer start filling from "started" label and end at "awaiting..." label. I try to add animation with CABasicAnimation it start from beginning but it not properly fill. Please check video like for more understanding.
func startProgressAnimation()
{
self.ivStarted.isHighlighted = true
let layer = CALayer()
layer.backgroundColor = #colorLiteral(red: 0.4980392157, green: 0.8352941176, blue: 0.1921568627, alpha: 1)
layer.masksToBounds = true
layer.frame = CGRect.init(x: self.viewStartedAwaited.frame.origin.x, y: self.viewStartedAwaited.frame.origin.y, width: 0.0, height: self.viewStartedAwaited.frame.height)
self.ivStarted.layer.addSublayer(layer)
CATransaction.begin()
let boundsAnim:CABasicAnimation = CABasicAnimation(keyPath: "bounds.size.width")
boundsAnim.fromValue = NSNumber.init(value: 0.0)
boundsAnim.byValue = NSNumber.init(value: Float(self.viewStartedAwaited.frame.size.width / 2.0))
boundsAnim.toValue = NSNumber.init(value: Float(self.viewStartedAwaited.frame.size.width))
let anim = CAAnimationGroup()
anim.animations = [boundsAnim]
anim.isRemovedOnCompletion = false
anim.duration = 5
anim.fillMode = kCAFillModeBoth
CATransaction.setCompletionBlock{ [weak self] in
self?.ivAwaited.isHighlighted = true
}
layer.add(anim, forKey: "bounds.size.width")
CATransaction.commit()
}
Here is the video what i achieve with this code. https://streamable.com/h6tpp
Not Proper
Proper image
Upvotes: 0
Views: 1003
Reputation: 1270
Just set your
layer.anchorPoint = CGPoint(x: 0, y: 0)
After this it will work according to your requirement.
The default anchorpoint of (0.5,0.5) means that the growing or shrinking of width happens evenly on both sides. Anchorpoint of (0,0) means the layer is essentially pinned to the top left, so whatever new width it gets, the change happens on the right. That is, it matters not whether your animation key path is 'bounds' or 'bounds.size.width'. The anchor point is what determines where the change happens
Upvotes: 3