(iOS) How to animate rounded rectangle with shapeLayer?
animation, cashapelayer, core-animation, ios, shapes
Solution
Doing this with a CAShapeLayer seems overly complicated to me if you are only using it for a rounded rectangle. Why not simply use a CALayer with the `cornerRadius` properly set?
Animating the frame with cornerRadius set will work fine.
myLayer = [CALayer layer];
shapeRect = CGRectMake(0.0f, 0.0f, 150.0f, 200.0f);
[myLayer setBounds:shapeRect];
[myLayer setPosition:CGPointMake(iniPosX, 80.0f)];
[myLayer setBackgroundColor:[[UIColor blackColor] CGColor]];
[myLayer setBorderColor:[[UIColor clearColor] CGColor]];
[myLayer setBorderWidth:1.0f];
[myLayer setOpacity:0.2];
[myLayer setCornerRadius:15.0];
[self.layer addSublayer:myLayer];
Animating it is done by simply chaining the frame (not the path)
- (void)adjustSelectorToPosAndSize:(float)posX andWidth:(float)width
{
shapeRect = CGRectMake(0.0f, 0.0f, width, 200.0f);
[myLayer setBounds:shapeRect];
[myLayer setPosition:CGPointMake(posX, 80.0f)];
}
Important:
Some of the properties changed name like `fillColor` became `backgroundColor` and the `strokeColor` and `lineWidth` became `borderColor` and `borderWidth` etc.
Problem
I am trying to animate the width of a rounded rectangle, the problem is when going from bigger width to thinner width, the animation does an "aberration ease jump". Here's the code: ``` shapeLayer = [CAShapeLayer layer]; shapeRect = CGRectMake(0.0f, 0.0f, 150.0f, 200.0f); [shapeLayer setBounds:shapeRect]; [shapeLayer setPosition:CGPointMake(iniPosX, 80.0f)]; [shapeLayer setFillColor:[[UIColor blackColor] CGColor]]; [shapeLayer setStrokeColor:[[UIColor clearColor] CGColor]]; [shapeLayer setLineWidth:1.0f]; [shapeLayer setLineJoin:kCALineJoinRound]; [shapeLayer setOpacity:0.2]; path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0]; [shapeLayer setPath:path.CGPath]; [self.layer addSublayer:shapeLayer]; ``` And when I start the animation: ``` - (void)adjustSelectorToPosAndSize:(float)posX andWidth:(float)width { shapeRect = CGRectMake(0.0f, 0.0f, width, 200.0f); [shapeLayer setBounds:shapeRect]; [shapeLayer setPosition:CGPointMake(posX, 80.0f)]; path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0]; [shapeLayer setPath:path.CGPath]; } ``` What am I doing wrong?