user2963333
user2963333

Reputation: 135

Draw line then delete it

with Xcode for iOS, I have animated a drawn line. I wish to delete it (or fade away) almost immediately. I have tried to repeat the code with the colour set to clear (red for the tests) as my background is a grid pattern. But I only get the last colour line drawn. Any ideas on drawing the lines in sequence one after each other?

{
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0.0,100.0)];
[path addLineToPoint:CGPointMake(150.0, 100.0)];
[path addLineToPoint:CGPointMake(155.0, 50.0)];
[path addLineToPoint:CGPointMake(160.0, 150.0)];
[path addLineToPoint:CGPointMake(165.0, 100.0)];
[path addLineToPoint:CGPointMake(350.0, 100.0)];


CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.view.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor greenColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 2.0f;
pathLayer.lineJoin = kCALineJoinBevel;

[self.view.layer addSublayer:pathLayer];

CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 1.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}

Thanks

Upvotes: 0

Views: 1021

Answers (2)

user2963333
user2963333

Reputation: 135

Thanks for all the help. I managed to find and successfully use code from the "Core Animation" Apple documentation. This is the first time I've managed that. Sorry for being slow, learning all the time. I had to replace "titleLayer" with "pathLayer". I'm sure that would have helped some of the suggestions. Thanks again.

Here's my working code. Added after the code I posted above, before the last curly bracket.

 CABasicAnimation* fadeAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];

fadeAnim.fromValue = [NSNumber numberWithFloat:1.0];

fadeAnim.toValue = [NSNumber numberWithFloat:0.0];

fadeAnim.duration = 1.5;

[pathLayer addAnimation:fadeAnim forKey:@"opacity"];



// Change the actual data value in the layer to the final value.

pathLayer.opacity = 0.0;

Upvotes: 0

David Berry
David Berry

Reputation: 41226

Add:

    pathAnimation.autoreverses = true;
    pathAnimation.removedOnCompletion = false;
    pathAnimation.fillMode = kCAFillModeForwards;

You'll also probably want to use the animation delegate functions to remove the layer on completion.

Alternatively, if you want a delay (even slight) before the animation reverses, or want to fade it out in a different manner than reversing the animation, you can use a CAAnimationGroup to execute a series of animations on the same timeline.

Upvotes: 1

Related Questions