How to draw line with animation in iPhone - iphone

I am drawing line in iphone using CGContextRef. Can any one suggest me how i draw line with animation in iphone.
Please suggest.

Here is the answer (found here : http://soulwithmobiletechnology.blogspot.fr/2012/07/how-to-animate-line-draw.html)
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50.0,0.0)];
[path addLineToPoint:CGPointMake(120.0, 600.0)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor redColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 2.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.view.layer addSublayer:pathLayer];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = 2.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:#"strokeEnd"];
Do not forget to #import <QuartzCore/QuartzCore.h>.

Is it a straight line?.. You can use a 1 pixel wide UIView and animate its frame property. Using [UIView beginAnimations] and [UIView commitAnimations]; Otherwise, see this post.
Edited response
Using core animation, you can do something like this (e.g. behind a button)
CABasicAnimation *theAnimation = [self pathAnimation];
theAnimation.duration=3.0;
theAnimation.autoreverses=YES;
[[self layer] addAnimation:theAnimation forKey:#"animatePath"];
Path animation is defined as:
- (CAAnimation*)pathAnimation;
{
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,50.0,120.0);
CGPathAddCurveToPoint(path,NULL,50.0,275.0,
150.0,275.0,
150.0,120.0);
CGPathAddCurveToPoint(path,NULL,150.0,275.0,
250.0,275.0,
250.0,120.0);
CGPathAddCurveToPoint(path,NULL,250.0,275.0,
350.0,275.0,
350.0,120.0);
CGPathAddCurveToPoint(path,NULL,350.0,275.0,
450.0,275.0,
450.0,120.0);
CAKeyframeAnimation *
animation = [CAKeyframeAnimation
animationWithKeyPath:#"position"];
[animation setPath:path];
[animation setDuration:3.0];
[animation setAutoreverses:YES];
CFRelease(path);
return animation;
}
This is only a pointer to what you can do with Core Animation. See this article for detail.

The Swift 3 version of Martin's answer (checked with Xcode 8.3.3)
let path = UIBezierPath()
path.move(to: CGPoint(x: 50, y: 0))
path.addLine(to: CGPoint(x: 120, y: 600))
let pathLayer = CAShapeLayer()
pathLayer.frame = view.bounds
pathLayer.path = path.cgPath
pathLayer.strokeColor = UIColor.red.cgColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 2
pathLayer.lineJoin = kCALineJoinBevel
view.layer.addSublayer(pathLayer)
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 2.0
pathAnimation.fromValue = 0
pathAnimation.toValue = 1
pathLayer.add(pathAnimation, forKey: "strokeEnd")

Related

CAShapeLayer LineCap not proper at end of CABasic Animation

I have implemented a basic line drawing animation for a progress bar.The line has a round cap edge.When I animated the line drawing the beginning of line is having a rounded cap but in the end its a square. below is the code I am using am i missing anything??
CAShape Layer Code :
CAShapeLayer *lineLayer = [[CAShapeLayer alloc] init];
[lineLayer setFrame: CGRectMake(0,
0,
wifisyncView.popUpView.frame.size.width,
wifisyncView.popUpView.frame.size.height)];
[lineLayer setPath: [linePath CGPath]];
lineLayer.lineWidth = 9.0f;
lineLayer.strokeEnd = 9.0f;
lineLayer.fillColor = [[UIColor orangeColor] CGColor];
lineLayer.lineCap = kCALineCapRound;
[lineLayer setStrokeColor:[[UIColor orangeColor] CGColor]];
[lineLayer setMasksToBounds:YES];
lineLayer.cornerRadius = 30.0f;
CABASIC Animation code :
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.duration = 5.0; // "animate over 5 seconds "
drawAnimation.repeatCount = 1.0; // Animate only once..
drawAnimation.removedOnCompletion = NO;// Remain stroked after the animation..
drawAnimation.fillMode = kCAFillModeForwards;
// Animate from no part of the stroke being drawn to the entire stroke being drawn
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
// Experiment with timing to get the appearence to look the way you want
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
drawAnimation.delegate = self;
// Add the animation to the circle
[lineLayer addAnimation:drawAnimation forKey:#"drawLineAnimation"];
Image Attached :
I dont find any mistakes in your code. I created a new project and pasted your code to viewDidLoad and is working fine. Code for your reference.
UIBezierPath *linePath = [UIBezierPath bezierPath];
[linePath moveToPoint:CGPointMake(100, 100)];
[linePath addLineToPoint:CGPointMake(500, 100)];
CAShapeLayer *lineLayer = [[CAShapeLayer alloc] init];
[lineLayer setFrame:self.view.bounds];
[lineLayer setPath: [linePath CGPath]];
lineLayer.lineWidth = 9.0f;
lineLayer.strokeEnd = 9.0f;
lineLayer.fillColor = [[UIColor orangeColor] CGColor];
lineLayer.lineCap = kCALineCapRound;
[lineLayer setStrokeColor:[[UIColor orangeColor] CGColor]];
[lineLayer setMasksToBounds:YES];
lineLayer.cornerRadius = 30.0f;
[self.view.layer addSublayer:lineLayer];
CABasicAnimation *drawAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
drawAnimation.duration = 5.0; // "animate over 5 seconds "
drawAnimation.repeatCount = 1.0; // Animate only once..
drawAnimation.removedOnCompletion = NO;// Remain stroked after the animation..
drawAnimation.fillMode = kCAFillModeForwards;
// Animate from no part of the stroke being drawn to the entire stroke being drawn
drawAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
drawAnimation.toValue = [NSNumber numberWithFloat:1.0f];
// Experiment with timing to get the appearence to look the way you want
drawAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
drawAnimation.delegate = self;
// Add the animation to the circle
[lineLayer addAnimation:drawAnimation forKey:#"drawLineAnimation"];
I think you should try changing
[lineLayer setFrame: CGRectMake(0,
0,
wifisyncView.popUpView.frame.size.width,
wifisyncView.popUpView.frame.size.height)];
to
[lineLayer setFrame: CGRectMake(0,
0,
wifisyncView.popUpView.bounds.size.width,
wifisyncView.popUpView.bounds.size.height)];

CAShapeLayer and animation position issue

I am making an iPhone app that draws a circle on the screen. I use a timer (every 5 second), so that I can 'grow' the circle, then wait 5 seconds then grow again. Now I am having trouble when animating the increase in size of the circle (I use paths and a CAShapeLayer layer). The size (from and to) are fine with the animation, its just when it starts the circle moves to the upper left hand side and grows from there. Any help or suggestions would be great. Thanks
The class where this is implemented is a UIControl, which is added to a UIView.
//Called in init method
(void) initalPop {
//Circle
self.bubble = [CAShapeLayer layer];
self.bubble.bounds = self.bounds;
self.bubble.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
self.bubble.fillColor = [
[UIColor greenColor] CGColor
];
self.bubble.strokeColor = [
[UIColor greenColor] CGColor
];
self.bubble.lineWidth = 4.0;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, nil, self.bounds);
self.bubble.path = path;
[self.layer addSublayer: self.bubble];
}
//Called when timer goes off
- (void) StageGrow {
CGFloat growSize = 50.0;
//Change the size of us and center the circle (but dont want to animate this
[CATransaction begin];
[CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
self.bounds = CGRectMake(0, 0, self.bounds.size.width + growSize, self.bounds.size.height + growSize);
self.bubble.position = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
[CATransaction commit];
[self ActualGrowCircle];
} - (void) ActualGrowCircle {
CGMutablePathRef oldPath = CGPathCreateMutable();
CGPathAddEllipseInRect(oldPath, nil, self.bubble.bounds);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, nil, self.bounds);
CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath: #"path"];
animation.duration = 2.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
animation.repeatCount = 1;
animation.delegate = self;
animation.autoreverses = NO;
animation.fromValue = (__bridge id) oldPath;
animation.toValue = (__bridge id) path;
self.bubble.bounds = self.bounds;
self.bubble.path = path;
[self.bubble addAnimation: animation forKey: #"animatePath"];
}
Let's say you're growing the bubble from size (100, 100) to size (150, 150).
You create oldPath as an ellipse in the rectangle (0, 0, 100, 100).
You create path as an ellipse in the rectangle (0, 0, 150, 150).
You set the bounds of the bubble layer to (0, 0, 150, 150), and you don't animate this change.
That means that oldPath will appear aligned to the top and left edges of the bubble layer.
One way to fix this is to create oldPath in a rectangle that is centered in the bubble's new bounds:
CGRect oldBubbleRect = CGRectInset(self.bounds, growSize / 2, growSize / 2);
CGPathRef oldPath = CGPathCreateWithEllipseInRect(oldBubbleRect, NULL);
By the way, you are leaking the paths you're creating. You need to call CGPathRelease on them after you're done with them.
Worked it out. In the long run I grouped the animations together and all became good (see code below). Thanks for your help Rob.
-(void)ActualGrowCircle {
CGMutablePathRef newPath = CGPathCreateMutable();
CGPathAddEllipseInRect(newPath, nil, self.bounds);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.repeatCount = 1;
animation.autoreverses = NO;
animation.fromValue = (__bridge id)self.bubble.path;
animation.toValue = (__bridge id)newPath;
CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:#"bounds"];
animation2.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation2.repeatCount = 1;
animation2.autoreverses = NO;
animation2.fromValue = [NSValue valueWithCGRect:self.bubble.bounds];
animation2.toValue = [NSValue valueWithCGRect:self.bounds];
CAAnimationGroup *group = [CAAnimationGroup animation];
[group setAnimations:[NSArray arrayWithObjects: animation2, animation, nil]];
group.duration = 0.5;
group.delegate = self;
self.bubble.bounds = self.bounds;
self.bubble.path = newPath;
[self.bubble addAnimation:group forKey:#"animateGroup"];
CGPathRelease(newPath);
}

How to animate CAShapeLayer path and fillColor

How to animate CAShapeLayer path and fillColor?
How to animate strokeEnd to show the path being drawn? and how to animate fillColor?
To animate path
//setup the CAShapeLayer
myShapeLayer.strokeColor = [[UIColor blueColor] CGColor];
myShapeLayer.lineWidth = 5;
myShapeLayer.fillColor = [[UIColor yellowColor] CGColor];
//Display it!
[self.view.layer addSublayer:myShapeLayer];
//Animate path
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = 1.5f;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
pathAnimation.repeatCount = 10;
pathAnimation.autoreverses = YES;
[myShapeLayer addAnimation:pathAnimation forKey:#"strokeEnd"];
//Animate colorFill
CABasicAnimation *fillColorAnimation = [CABasicAnimation animationWithKeyPath:#"fillColor"];
fillColorAnimation.duration = 1.5f;
fillColorAnimation.fromValue = (id)[[UIColor clearColor] CGColor];
fillColorAnimation.toValue = (id)[[UIColor yellowColor] CGColor];
fillColorAnimation.repeatCount = 10;
fillColorAnimation.autoreverses = YES;
[myShapeLayer addAnimation:fillColorAnimation forKey:#"fillColor"];
I hope this helps :)
2021 Update
Swift
myShapeLayer.strokeColor = UIColor.blue.cgColor
myShapeLayer.lineWidth = 5
myShapeLayer.fillColor = UIColor.yellow.cgColor
//Display it!
view.layer.addSublayer(myShapeLayer)
//Animate path
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 1.5
pathAnimation.fromValue = NSNumber(value: 0.0)
pathAnimation.toValue = NSNumber(value: 1.0)
pathAnimation.repeatCount = 10
pathAnimation.autoreverses = true
myShapeLayer.add(pathAnimation, forKey: "strokeEnd")
//Animate colorFill
let fillColorAnimation = CABasicAnimation(keyPath: "fillColor")
fillColorAnimation.duration = 1.5
fillColorAnimation.fromValue = UIColor.clear.cgColor
fillColorAnimation.toValue = UIColor.yellow.cgColor
fillColorAnimation.repeatCount = 10
fillColorAnimation.autoreverses = true
myShapeLayer.add(fillColorAnimation, forKey: "fillColor")

Animate the drawing of lines in UIView

Can anybody please help me with this problem? I have the nsarray of lines and I need to write them one after the other within some UIView (I want to animate the hand drawing).
Here is the answer (found here : http://soulwithmobiletechnology.blogspot.fr/2012/07/how-to-animate-line-draw.html)
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(50.0,0.0)];
[path addLineToPoint:CGPointMake(120.0, 600.0)];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor redColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 2.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.view.layer addSublayer:pathLayer];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = 2.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:#"strokeEnd"];
Do not forget to #import <QuartzCore/QuartzCore.h>.
Some entry points that might help :
Apple documentations: Core Animation, Quartz 2D and Quartz Demo Sample code
Some Core Animation samples
this code animates an object over a set of points. can use same idea for your lines, which i assume are CGPath?
//
// animate along a set of points
//
// NSLog(#"The content of movement1PointsArray is%#",movement1PointsArray);
CGMutablePathRef touchPath1 = CGPathCreateMutable();
CGPoint touchPath1StartPoint = [[movement1PointsArray objectAtIndex:0] CGPointValue];
CGPathMoveToPoint(touchPath1,NULL,touchPath1StartPoint.x, touchPath1StartPoint.y);
for (NSInteger p = 0; p < [movement1PointsArray count]; ++p)
{
CGPoint touchesPointOnPath = [[movement1PointsArray objectAtIndex:p] CGPointValue];
CGPathAddLineToPoint(touchPath1, NULL,touchesPointOnPath.x,touchesPointOnPath.y);
}
CAKeyframeAnimation* touchPathAnimation1 = [CAKeyframeAnimation animationWithKeyPath:#"position"];
[touchPathAnimation1 setDuration: 1.0];
[touchPathAnimation1 setAutoreverses: NO];
touchPathAnimation1.removedOnCompletion = NO;
touchPathAnimation1.fillMode = kCAFillModeForwards;
[touchPathAnimation1 setPath: touchPath1];
CFRelease(touchPath1);
[animationsArray addObject:touchPathAnimation1];
[ball.layer addAnimation: touchPathAnimation1 forKey: #"position"];
i am having trouble getting a second path to animate...regardless of what i try, it only animates the last path.
You probably end up implementing the views drawRect method.
This http://howtomakeiphoneapps.com/2009/08/how-to-draw-shapes-with-core-graphics/
Should get you started

iPhone CALayer animation

I am drawing a line animation, connecting 2 points with a line. This is my code:
-(void) drawObject{
rootLayer = [CALayer layer];
rootLayer.frame = self.view.bounds;
[self.view.layer addSublayer:rootLayer];
lineStartPath = CGPathCreateMutable();
CGPathMoveToPoint(lineStartPath, nil, 160, 50);
CGPathAddLineToPoint(lineStartPath, nil, 160, 50);
CGPathCloseSubpath(lineStartPath);
lineEndPath = CGPathCreateMutable();
CGPathMoveToPoint(lineEndPath, nil, 160, 50);
CGPathAddLineToPoint(lineEndPath, nil, 160, 300);
CGPathCloseSubpath(lineEndPath);
shapeLayer = [CAShapeLayer layer];
shapeLayer.path = lineStartPath;
UIColor *strokeColor = [UIColor colorWithHue:0.557 saturation:0.55 brightness:0.96 alpha:1.0];
shapeLayer.strokeColor = strokeColor.CGColor;
shapeLayer.lineWidth = 3.0;
[rootLayer addSublayer:shapeLayer];
[self performSelector:#selector(startAnimation) withObject:nil afterDelay:1.0];
}
-(void) startAnimation{
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.duration = 0.5;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
animation.fromValue = (id)lineStartPath;
animation.toValue = (id)lineEndPath;
[shapeLayer addAnimation:animation forKey:#"animatePath"];
}
The weak point is after the animation is ended, the line disappears. I want that after my line is drawn between those 2 points, id does not disappear. Give me a hint please.
Try adding
shapeLayer.path = lineEndPath;
at the beginning of startAnimation.
It's explained in this video: Session 424 - Core Animation in Practice, Part 1 from the WWDC 2010 (around 38:00).
and replace [shapeLayer addAnimation:animation forKey:#"animatePath"]; with [shapeLayer addAnimation:animation forKey:#"path"];.