How to Animate CoreGraphics Drawing of Shape Using CAKeyframeAnimation - uiview

I am trying to animate the drawing of a UIBeizerPath (in my example a triangle) in a UIView subclass. However, the entire subview is animating instead of the shape.
Is there something I am missing with the animation?
- (void)drawRect:(CGRect)rect {
CAShapeLayer *drawLayer = [CAShapeLayer layer];
drawLayer.frame = CGRectMake(0, 0, 100, 100);
drawLayer.strokeColor = [UIColor greenColor].CGColor;
drawLayer.lineWidth = 4.0;
[self.layer addSublayer:drawLayer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0,0)];
[path addLineToPoint:CGPointMake(50,100)];
[path addLineToPoint:CGPointMake(100,0)];
[path closePath];
CGPoint center = [self convertPoint:self.center fromView:nil];
[path applyTransform:CGAffineTransformMakeTranslation(center.x, center.y)];
[[UIColor redColor] set];
[path fill];
[[UIColor blueColor] setStroke];
path.lineWidth = 3.0f;
[path stroke];
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.duration = 4.0f;
pathAnimation.path = path.CGPath;
pathAnimation.calculationMode = kCAAnimationLinear;
[drawLayer addAnimation:pathAnimation forKey:#"position"];
}

You are creating a CAShapeLayer, but then not doing anything useful with it. Let's fix that.
Don't set up layers and animations in -drawRect:, because that's strictly meant as a time to do drawing using the CoreGraphics or UIKit APIs. Instead, you want the CAShapeLayer to draw the triangle -- that way you can animate it.
CAKeyframeAnimation.path is meant for something completely different (e.g. moving a layer along a path).
Your animation is animating the position value of the layer. No surprise that it moves the layer! You want to animate the path value instead.
The idea behind CAKeyframeAnimation is that you provide it an array of values to set the layer's property to. During the time between keyframes, it will interpolate between the two adjacent keyframes. So you need to give it several paths -- one for each side.
Interpolating arbitrary paths is difficult. CA's path interpolation works best when the paths have the same same number and kind of elements. So, we make sure all our paths have the same structure, just with some points on top of each other.
The secret to animation, and maybe to computers in general: you must be precise in explaining what you want to happen. "I want to animate the drawing of each point, so it appears to be animated" is not nearly enough information.
Here's a UIView subclass that I think does what you're asking for, or at least close. To animate, hook a button up to the -animate: action.
SPAnimatedShapeView.h:
#import <UIKit/UIKit.h>
#interface SPAnimatedShapeView : UIView
- (IBAction)animate:(id)sender;
#end
SPAnimatedShapeView.m:
#import "SPAnimatedShapeView.h"
#import <QuartzCore/QuartzCore.h>
#interface SPAnimatedShapeView ()
#property (nonatomic, retain) CAShapeLayer* shapeLayer;
#end
#implementation SPAnimatedShapeView
#synthesize shapeLayer = _shapeLayer;
- (void)dealloc
{
[_shapeLayer release];
[super dealloc];
}
- (void)layoutSubviews
{
if (!self.shapeLayer)
{
self.shapeLayer = [[[CAShapeLayer alloc] init] autorelease];
self.shapeLayer.bounds = CGRectMake(0, 0, 100, 100); // layer is 100x100 in size
self.shapeLayer.position = self.center; // and is centered in the view
self.shapeLayer.strokeColor = [UIColor blueColor].CGColor;
self.shapeLayer.fillColor = [UIColor redColor].CGColor;
self.shapeLayer.lineWidth = 3.f;
[self.layer addSublayer:self.shapeLayer];
}
}
- (IBAction)animate:(id)sender
{
UIBezierPath* path0 = [UIBezierPath bezierPath];
[path0 moveToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
[path0 addLineToPoint:CGPointZero];
UIBezierPath* path1 = [UIBezierPath bezierPath];
[path1 moveToPoint:CGPointZero];
[path1 addLineToPoint:CGPointMake(50,100)];
[path1 addLineToPoint:CGPointMake(50,100)];
[path1 addLineToPoint:CGPointMake(50,100)];
UIBezierPath* path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointZero];
[path2 addLineToPoint:CGPointMake(50,100)];
[path2 addLineToPoint:CGPointMake(100,0)];
[path2 addLineToPoint:CGPointMake(100,0)];
UIBezierPath* path3 = [UIBezierPath bezierPath];
[path3 moveToPoint:CGPointZero];
[path3 addLineToPoint:CGPointMake(50,100)];
[path3 addLineToPoint:CGPointMake(100,0)];
[path3 addLineToPoint:CGPointZero];
CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:#"path"];
animation.duration = 4.0f;
animation.values = [NSArray arrayWithObjects:(id)path0.CGPath, (id)path1.CGPath, (id)path2.CGPath, (id)path3.CGPath, nil];
[self.shapeLayer addAnimation:animation forKey:nil];
}
#end

Related

Draw on UIView or GLKView?

I need to draw a separator line with some dots on it. I have decided I will do this using the draw method, as opposed to including images of the separator. I will do this for performance and for customisability, as the separator changes sometimes.
Now I have looked into the draw() method on UIView and I have noticed that Apple suggests using GLKView when drawing using OpenGL.
For a simple separator, won't it be too much of a hassle to call OpenGL? Or is the OpenGL overhead negligible? When would I want to use the native UIKit draw() then?
FYI I don't know either method, but want to learn both methods, so don't reply "what you know best". I am simply asking about performance.
OpenGL uses GPU instead of CPU for computation. If you are making something like a gaming app, then you can think of using OpenGL. I believe you want to draw a line in an iOS App. For that you can either use drawRect method in UIView or create a shapeLayer and add it as a sublayer.
The following examples will show you:
CAShapeLayer *simpleLine = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 80)];
[path addLineToPoint:CGPointMake(300, 80)];
simpleLine.lineWidth = 1.0;
simpleLine.path = path.CGPath;
simpleLine.strokeColor = [[UIColor blackColor] CGColor];
[[self.view layer] addSublayer:simpleLine];
For using drawRect, you are supposed to do this inside a Custom UIView as opposed to the above method.
- (void)drawRect:(CGRect)rect {
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 80)];
[path addLineToPoint:CGPointMake(300, 80)];
path.lineWidth = 1.0;
[[UIColor blueColor] setStroke];
[path stroke];
}
If your separator parameters changes and if you are making an app, it's better to use drawRect method. You can call this method anytime by using [CustomUIView setNeedsDisplay:YES]
Edit
What you're asking for is circle over line. You can do that by drawing UIBezierPath for line first and then add UIBezierPath for circle later.
Normal Line
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10.0, 10.0)];
[path addLineToPoint:CGPointMake(100.0, 100.0)];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
[self.view.layer addSublayer:shapeLayer];
Dotted Line
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(10.0, 10.0)];
[path addLineToPoint:CGPointMake(100.0, 100.0)];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
shapeLayer.lineDashPattern = #[#4, #2];
[self.view.layer addSublayer:shapeLayer];

Animate CAShapeLayer setPath

I am trying to add animation while drawing a bezierPath. There is base circle darkgray (0 to 360) , green path (-90 to 0) and red path (0 to 90).
#import "ProgressBar.h"
#interface ProgressBar ()
{
CAShapeLayer *lightGrayPath;
}
#end
#implementation ProgressBar
-(id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
[self initValues];
}
return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
[self initValues];
}
return self;
}
-(void)awakeFromNib{
[super awakeFromNib];
[self startAnimation];
}
-(void)initValues{
lightGrayPath = [CAShapeLayer layer];
lightGrayPath.fillColor = [UIColor clearColor].CGColor;
lightGrayPath.lineWidth=2.0f;
lightGrayPath.strokeColor =[UIColor colorWithWhite:0 alpha:0.1].CGColor;
[self.layer addSublayer:lightGrayPath];
}
-(void)startAnimation{
CGRect rect=self.bounds;
CGFloat subPathWidth=10.0;
UIBezierPath *bezierPath_lightGray=[UIBezierPath bezierPath];
bezierPath_lightGray.lineWidth=lightGrayPath.lineWidth;
[bezierPath_lightGray addArcWithCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) radius:(rect.size.height / 2)- subPathWidth/2.0
startAngle:0 endAngle:2*M_PI clockwise:YES];
UIBezierPath *bezierPath_green=[UIBezierPath bezierPath];
bezierPath_green.lineWidth=subPathWidth;
[[UIColor greenColor] setStroke];
[bezierPath_green addArcWithCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) radius:(rect.size.height / 2)- subPathWidth/2.0 startAngle:-M_PI/2.0 endAngle:0 clockwise:YES];
[bezierPath_green stroke];
[bezierPath_lightGray appendPath:bezierPath_green];
UIBezierPath *bezierPath_red=[UIBezierPath bezierPath];
bezierPath_red.lineWidth=subPathWidth;
[[UIColor redColor] setStroke];
[bezierPath_red addArcWithCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) radius:(rect.size.height / 2)- subPathWidth/2.0 startAngle:0 endAngle:M_PI_2 clockwise:YES];
[bezierPath_red stroke];
[bezierPath_lightGray appendPath:bezierPath_red];
lightGrayPath.path=bezierPath_lightGray.CGPath;
// CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"path"];
// pathAnimation.duration = 10.0;
// //pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
// pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
// [lightGrayPath addAnimation:pathAnimation forKey:#"path"];
}
#end
I want to show animation of path being drawn. The lightGrayArc should not be animated. The Green arc and the red arc should be.
But, Since I am using only one CAShapeLayer and appending paths to it. When i use animation , it animates the light gray path, no animation for green and red arc.
I would suggest:
Do not animate in drawRect. That's for drawing a single frame.
There are two ways to animate a path:
Don't use CAShapeLayer at all, but instead define a drawRect that performs stroke on one or more UIBezierPath.
To animate, don't use CABasicAnimation, but rather use a CADisplayLink (a type of timer optimized for screen updates) that changes some properties that define where the path starts and ends and then call setNeedsDisplay, which will trigger a call to drawRect that will use those properties to stroke the path for that frame of the animation.
Even easier, don't use drawRect to stroke anything at all. Just add your gray, green, and red arcs as three different CAShapeLayer instances. Let CAShapeLayer do all the rendering of the arcs for you.
When you want to animate the red and green layers, add CABasicAnimation for those respective layers.

How can i remove the circle drawn in iOS?

I have this code where I draw circles on the screen, and I want to remove just the last circle drawn. What can I do? The code is set to draw a circle when I tap twice. I want to remove the last circle drawn when I tap one time.
- (UIBezierPath *)makeCircleAtLocation:(CGPoint)location radius:(CGFloat)radius {
iOSCircle *circle = [[iOSCircle alloc] init];
circle.circleCenter = location;
circle.circleRadius = radius;
[totalCircles addObject:circle];
UIBezierPath *path = [UIBezierPath bezierPath];
[path addArcWithCenter:circle.circleCenter
radius:circle.circleRadius
startAngle:0.0
endAngle:M_PI * 2.0
clockwise:YES];
return path;
}
- (IBAction) tapEvent: (UIGestureRecognizer *) sender
{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [[self makeCircleAtLocation:location radius:2.5] CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
//shapeLayer.fillColor = nil;
shapeLayer.lineWidth = 2.5;
// Add CAShapeLayer to our view
[self.view.layer addSublayer:shapeLayer];
// Save this shape layer in a class property for future reference,
// namely so we can remove it later if we tap elsewhere on the screen.
self.circleLayer = shapeLayer;
}
}
Create your circle in a distinct CAShapeLayer layer using a CGPath, and add it as a sublayer of your view.layer. That way, you will have total control over that circle (showing or hiding it).

How to draw a rectangle with an animated stroke

I know how to draw a rectangle outline to the screen with something like this:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGPathRef path = CGPathCreateWithRect(rect, NULL);
[[UIColor greenColor] setStroke];
CGContextAddPath(context, path);
CGContextDrawPath(context, kCGPathFillStroke);
CGPathRelease(path);
}
But what I want is to have the "pen" start at the top center of the rectangle and draw around the edges at some variable speed, so that you can actually see the rectangle getting drawn as the "pen" moves. Is this possible? How?
You could easily use a CALayerShape with a Pen Image and do it like this (I added a button to the view which triggered the drawing):
#import "ViewController.h"
#interface ViewController () {
UIBezierPath *_drawPath;
CALayer *_pen;
UIBezierPath *_penPath;
CAShapeLayer *_rectLayer;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *penImage = [UIImage imageNamed:#"pen"];
_drawPath = [UIBezierPath bezierPathWithRect:self.view.frame];
_penPath = [UIBezierPath bezierPath];
[_penPath moveToPoint:CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(self.view.frame.size.width - penImage.size.width/2.f, penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(self.view.frame.size.width - penImage.size.width/2.f, self.view.frame.size.height - penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(penImage.size.width/2.f, self.view.frame.size.height - penImage.size.height/2.f)];
[_penPath addLineToPoint:CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f)];
_rectLayer = [[CAShapeLayer alloc] init];
_rectLayer.path = _drawPath.CGPath;
_rectLayer.strokeColor = [UIColor greenColor].CGColor;
_rectLayer.lineWidth = 5.f;
_rectLayer.fillColor = [UIColor clearColor].CGColor;
_rectLayer.strokeEnd = 0.f;
[self.view.layer addSublayer:_rectLayer];
_pen = [CALayer layer];
_pen.bounds = CGRectMake(0, 0, 25.f, 25.f);
_pen.position = CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f);
_pen.contents = (id)(penImage.CGImage);
_pen.position = CGPointMake(penImage.size.width/2.f, penImage.size.height/2.f);
[self.view.layer addSublayer:_pen];
}
- (IBAction)drawRectangle:(id)sender
{
_rectLayer.strokeEnd = 1.f;
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
anim.fromValue = (id)[NSNumber numberWithFloat:0];
anim.toValue = (id)[NSNumber numberWithFloat:1.f];
anim.duration = 5.f;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[_rectLayer addAnimation:anim forKey:#"drawRectStroke"];
CAKeyframeAnimation *penMoveAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
penMoveAnimation.path = _penPath.CGPath;
penMoveAnimation.rotationMode = kCAAnimationRotateAuto;
penMoveAnimation.duration = 5.0;
penMoveAnimation.calculationMode = kCAAnimationPaced;
[_pen addAnimation:penMoveAnimation forKey:#"followStroke"];
}
EDIT: Added code for pen to follow stroke, heres the 2x image used: http://cl.ly/image/173J271Y003B
Note: The only problem is that when the pen gets closer to the rotating point or corner its still paced with the stroke therefore the pen looks like its behind the stroke a bit until it flips, a simple solution might be to arc the curve, but Im not sure what your overall goal is.

How to Make CABasicAnimation invisible outside of superLayer bounds?

I'm trying to move a triangle from outside of the UIView bounds into the UIView area.
I'm using UIBezierPath.
While the triangle is outside of the area, I want it to be invisible.
I want only the part of the triangle that is inside the UIView to be visible.
Unfortunately it is visible throughout the animation (while outside of bounds and inside).
This is my code:
UIBezierPath *triangle = [UIBezierPath bezierPath];
[triangle moveToPoint:CGPointMake(X, Y)];
[triangle addLineToPoint:CGPointMake(X - (width*0.5), Y)];
[triangle addLineToPoint:CGPointMake(X, Y + (width*0.5))];
[triangle closePath];
CAShapeLayer *triLayer = [CAShapeLayer layer];
triLayer.frame = testView.bounds;
triLayer.path = triangle.CGPath;
triLayer.strokeColor = [[UIColor redColor] CGColor];
triLayer.fillColor = [[UIColor yellowColor] CGColor];
[testView.layer addSublayer:triLayer];
CABasicAnimation *triangleAnimation = [CABasicAnimation animationWithKeyPath:#"transform.translation.x"];
triangleAnimation.duration=0.5;
triangleAnimation.repeatCount=1;
triangleAnimation.autoreverses=NO;
triangleAnimation.fromValue=[NSNumber numberWithFloat:(width*0.5)];
triangleAnimation.toValue=[NSNumber numberWithFloat:0];
triangleAnimation.removedOnCompletion = NO;
triangleAnimation.fillMode = kCAFillModeForwards;
[triLayer addAnimation:triangleAnimation forKey:#"animateLayer"];
If you have a reference to the superview itself, you can set the clipsToBounds property on it to YES. Otherwise, you can use the CALayer's masksToBounds property to do the same thing.
Use
testView.layer.masksToBounds = YES;

Resources