Animate CAShapeLayer's bezier path with animation from center - ios

I'm trying to animate a chart so it scales from the center. Now it scales from left to right.
Initial State:
Final State:
Animation:
Here is my code:
maskLayer = [[CAShapeLayer alloc] init];
maskLayer.borderColor=[UIColor redColor].CGColor;
maskLayer.borderWidth=1;
maskLayer.fillColor=UIColorFromRGB(0x91E5FF).CGColor;
maskLayer.frame = CGRectMake(0,0, rect.size.width, rect.size.height);
maskLayer.path = finalPath.CGPath;
maskLayer.opacity=0.8;
[self.layer addSublayer:maskLayer];
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"path"];
anim.duration = 4;
anim.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.removedOnCompletion = NO;
anim.fillMode = kCAFillModeBoth;
anim.fromValue = (id)[initialPath CGPath];
anim.toValue= (id)[finalPath CGPath];
[maskLayer addAnimation:anim forKey:nil];

To get the results you want, you can't just scale - you'll have the same path at the start and finish. Your stated example has a path animation.
All you have to do is draw your paths in relation to each other, the way you want them to animate. If you want to animate your path as if it's anchored in the center, you need to draw them like that. Center both your paths on each other.
Here's a simple example:
UIBezierPath* initialPath = [UIBezierPath bezierPathWithRect: CGRectMake(-25, -25, 50, 50)];
UIBezierPath* finalPath = [UIBezierPath bezierPathWithRect: CGRectMake(-40, -40, 80, 80)];
In this example, your square will scale up from the center. If your path is currently scaling from the right, it's because thats where your paths are aligned.

Related

Circle strokeWidth change animation without changing the circle radius

I have a few rects that I draw a circle in with UIBezierPath and CAShapeLayer. They should act like buttons, in which when they are tapped they are being selected and when a different button is tapped they are being deselected, where each of these states should change button appearance between these two conditions:
deselected: selected:
This is the general code (which is called when selection changes):
CGFloat radius = isSelected ? 9.8 : 13. ;
CGFloat strokeWidth = isSelected ? 10.5 : 2;
UIBezierPath *bezierPath = [UIBezierPath bezierPath];
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
[bezierPath addArcWithCenter:center radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES];
CAShapeLayer *progressLayer = [[CAShapeLayer alloc] init];
[progressLayer setPath:bezierPath.CGPath];
[progressLayer setStrokeColor:[UIColor redColor].CGColor];
[progressLayer setLineWidth:strokeWidth]];
[self.layer addSublayer:progressLayer];
When this rect is selected, I would like to change the strokeWidth of the circle only inward, and keep the original radius. When it's deselected, the opposite should happen.
As you can see I change both the radius and the lineWidth, because when I make strokeWidth bigger, the outer radius is growing as well. And as I said, I want to keep it the same.
The problem is that I want it animated in a way that the width grows inward when selected, and out when deselected, without changing the outer radius at all.
What I have so far, is an animation of the change of strokeWidth together with the radius in order to keep the result with the same appeared radius. But it's not what I need. As you can see, only the radius change is animated here, and the result is a growing circle, which I don't want.
This is the code of the animation (in addition to the original code):
CABasicAnimation *changeCircle = [CABasicAnimation animationWithKeyPath:#"path"];
changeCircle.duration = 0.6;
changeCircle.fromValue = (__bridge id)oldPath; // current bezier path
changeCircle.toValue = (__bridge id)newPath; // new bezier path
[progressLayer addAnimation:changeCircle forKey:nil];
I had also the opposite code, that animates only the change of strokeWidth. It also doesn't do what I need.
Is there a way to the strokeWidth grow or get small without changing the outer radius?
Like this:
Thanks to #Chris, I managed to work it out.
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"path"];
pathAnimation.fromValue = (__bridge id) oldPath;
pathAnimation.toValue = (__bridge id) newPath;
CABasicAnimation *lineWidthAnimation = [CABasicAnimation animationWithKeyPath:#"lineWidth"];
lineWidthAnimation.fromValue = isSelected ? #2. : #10.5;
lineWidthAnimation.toValue = isSelected ? #10.5 : #2.;
CAAnimationGroup *group = [CAAnimationGroup animation];
group.duration = 0.3;
group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
group.animations = #[pathAnimation, lineWidthAnimation];
CAShapeLayer *progressLayer = [[CAShapeLayer alloc] init];
[progressLayer setPath:bezierPath.CGPath];
[progressLayer setStrokeColor:self.color.CGColor];
[progressLayer setLineWidth:isSelected ? 10.5 : 2];
[progressLayer setFillColor:[UIColor clearColor].CGColor];
[progressLayer addAnimation:group forKey:#"selectedAnimations"];
[self.layer addSublayer:progressLayer];

How to animate drawing part of CGPath

I want to approach the following scenario:
If I draw a rectangle using CGBezierPath and CAShapeLayer like the following:
CAShapeLayer *layerX = [CAShapeLayer layer];
layerX.path = path.CGPath;
layerX.lineWidth = 3;
layerX.strokeColor = [[UIColor whiteColor] CGColor];
layerX.fillColor = [[UIColor clearColor] CGColor];
[self.view.layer addSublayer: layerX];
And I want to add animation like the image I attached, this cleared area keeps moving around the rectangle path so it gives visual effect of the rectangle being drawn over and over. [Snake movement in old snake games]
I tried animating using CABasicAnimation but I literally couldn't achieve anything, thanks in advance.
Try this code may be helpful.
UIBezierPath *drawablePath = [UIBezierPath bezierPathWithRect:CGRectMake(100.0, 100.0, 150.0, 100.0)];
CAShapeLayer *squareLayer = [[CAShapeLayer alloc] init];
squareLayer.path = drawablePath.CGPath;
squareLayer.strokeColor = [UIColor redColor].CGColor;
squareLayer.lineWidth = 5.f;
squareLayer.fillColor = [UIColor clearColor].CGColor;
squareLayer.strokeEnd = 1.f;
//squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
[self.view.layer addSublayer:squareLayer];
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.fromValue = (id)[NSNumber numberWithFloat:0.10];
drawAnimation.toValue = (id)[NSNumber numberWithFloat:1.f];
drawAnimation.duration = 5.f;
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[squareLayer addAnimation:drawAnimation forKey:#"drawRectStroke"];
This code is use to draw rectangle with animation.
You have to animate both: strokeStart and strokeEnd and use a CAAnimationGroup to make them happen at the same time.
I found this link which does something similar but in swift. I think it might help.
I will try to implement it if you can't do it. But I can't right now.
Happy coding.
let drawablePath = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 150, height: 150))
let squareLayer = CAShapeLayer()
squareLayer.path = drawablePath.cgPath;
squareLayer.strokeColor = UIColor.red.cgColor;
squareLayer.lineWidth = 5;
squareLayer.fillColor = UIColor.clear.cgColor;
squareLayer.strokeEnd = 1;
//squareLayer.strokeEnd = 0.9; // this line use draw half line but some animation issue.
flowerView.layer.addSublayer(squareLayer)
let drawAnimation = CABasicAnimation(keyPath: "strokeEnd")
drawAnimation.fromValue = 0.1
drawAnimation.toValue = 1.0
drawAnimation.duration = 5
drawAnimation.timingFunction = CAMediaTimingFunction(name:.linear)
squareLayer.add(drawAnimation, forKey:"drawRectStroke")
Not really an answer to the original question but here's a Swift 5 version of Dixit Akabari's answer, which was useful in itself in that it demonstrates how to animate drawing a UIBezierPath by animating strokeEnd.

UIView circle mask animation

I have an abstract strange shaped UIView.
And I need to display a smooth appearance animation.
I assume I should apply that animation to the mask above that view.
The mask is going to be circle shaped.
So user will see the 1'2'3'4' sequence.
How can I implement that?
I suppose I should apply some affine transformation
to the mask view. In that case, what should be the original shape of the mask?
A vertical line?
A simple example,suppose I have a 100*100 imageview,
Note:to make it simple,I use hard code numbers
CAShapeLayer * maskLayer = [CAShapeLayer layer];
maskLayer.bounds = CGRectMake(0, 0, 100, 100);
maskLayer.position = CGPointMake(50, 50);
UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(50.0, 50.0) radius:50 startAngle:0 endAngle:M_PI *2 clockwise:true];
maskLayer.path = path.CGPath;
maskLayer.fillColor = [UIColor clearColor].CGColor;
maskLayer.strokeColor = [UIColor blackColor].CGColor;
maskLayer.strokeEnd = 0.0;
maskLayer.lineWidth = 100;
self.imageview.layer.mask = maskLayer;
CABasicAnimation * animation = [CABasicAnimation animation];
animation.keyPath = #"strokeEnd";
animation.toValue = #(1.0);
animation.duration = 2.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
[maskLayer addAnimation:animation forKey:#"keyFrame"];

iOS - Animate only the 'appendPath' of an UIBezierPath

there are a lot of examples how to animate along a UIBezierPath. But i can't figure it out, how to animate only the appendPath of an UIBezierPath.
In my case i have the following example:
// Create path from view controller
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:
CGRectMake(0, 0, tutorialController.bounds.size.width,
tutorialController.bounds.size.height) cornerRadius:0];
// Create circle path
UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x, y, 2.0*radius, 2.0*radius) cornerRadius:radius];
[path appendPath:circlePath];
[path setUsesEvenOddFillRule:YES];
// Create spot layer
spotLayer = [CAShapeLayer layer];
spotLayer.path = path.CGPath;
spotLayer.fillRule = kCAFillRuleEvenOdd;
spotLayer.fillColor = [UIColor blackColor].CGColor;
spotLayer.opacity = 0.90;
So basically its a circle inside a rect and i now want to animate only the circle. In all attempts the rect was also moved.
Here is my example, how i can animate "along" a path
CGPoint pathStart = CGPointMake(96.000000, 226.000000);
CGPoint pathEnd = CGPointMake(120.000000, 300.000000);
[circlePath moveToPoint:pathStart];
[circlePath addLineToPoint:pathEnd];
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
anim.path = circlePath.CGPath;
anim.duration = 5.0;
anim.calculationMode = kCAAnimationPaced;
[spotLayer addAnimation:anim forKey:#"bezierPathAnim"];
But that is not what i want...
What i want to do is, to move my circle path (which is an appended path of a rectangle path) via animation
Does anybody has some ideas?
Regards
I solved my Problem :-)
Here is the solution...
// If there is an old path animate to the new path
if(oldPath != nil){
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"path"];
[anim setFromValue:(__bridge id)oldPath];
[anim setToValue:(__bridge id)[path CGPath]];
[anim setDuration:0.3];
[anim setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[spotLayer addAnimation:anim forKey:#"path"];
}
First of all i kept the oldPath (starting point) and then animate to the new setted path.

How to put 2 layers to follow same bezierpath without one hiding the other

I have created 2 CALayers of same size and am passing these to the method below. However, the two layers runs together. How can I seperate these so that both are visible?
- (void) myAnimation : (CALayer *) sublayer {
UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(30, 100, 270, 270)];
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
anim.path = aPath.CGPath;
anim.rotationMode = kCAAnimationRotateAuto;
anim.repeatCount = HUGE_VALF;
anim.duration =35.0;
[sublayer addAnimation:anim forKey:#"race"];
}
Your path begins and ends at the same point. Assuming both beginning times are the same and duration is the same, your layers will precisely overlap. You can either shift the beginning time or rotate your UIBezierPath* aPath Here's an example of rotating your UIBezierPath* aPath and altering the duration. It should give you an idea how you could alter duration, begin time, rotation, etc.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor blackColor]];
CALayer * layer1 = [CALayer layer];
CALayer * layer2 = [CALayer layer];
[layer1 setFrame:CGRectMake(0, 0, 5, 50)];
[layer2 setFrame:CGRectMake(0, 0, 5, 100)];
layer1.backgroundColor = [[UIColor colorWithRed:.1 green:.5 blue:1 alpha:.35] CGColor];
layer2.backgroundColor = [[UIColor colorWithRed:.9 green:.2 blue:.5 alpha:.35] CGColor];
[self.view.layer addSublayer:layer1];
[self.view.layer addSublayer:layer2];
[self myAnimation:layer1 andRotation:0 andDuration:35.0];
[self myAnimation:layer2 andRotation:10 andDuration:10.0];
}
- (void) myAnimation:(CALayer *)sublayer andRotation:(CGFloat)rot andDuration:(CFTimeInterval)dur {
CGRect rect = CGRectMake(30, 100, 270, 270);
UIBezierPath* aPath = [UIBezierPath bezierPathWithOvalInRect:rect];
// Creating a center point around which we will transform the path
CGPoint center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformTranslate(transform, center.x, center.y);
transform = CGAffineTransformRotate(transform, rot);
// Recenter the transform
transform = CGAffineTransformTranslate(transform, -center.x, -center.y);
// This is the new path we will use.
CGPathRef rotated = CGPathCreateCopyByTransformingPath(aPath.CGPath, &transform);
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
anim.path = rotated;
anim.rotationMode = kCAAnimationRotateAuto;
anim.repeatCount = HUGE_VALF;
anim.duration =dur;
[sublayer addAnimation:anim forKey:#"race"];
}

Resources