Search code examples
calayeruibezierpathcabasicanimationcashapelayerpulse

UIBezierPath pulse animation


I'm drawing a UIBezierPath on a UIScrollView I have made an animation that draws the path from start to end point but this is not the animation that I want.

   UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:startPoints];  
    [linePath addLineToPoint:endPoints; 


    //shape layer for the line
    CAShapeLayer *line = [CAShapeLayer layer];
    line.path = [linePath CGPath];
    // line.fillColor = [[UIColor blackColor] CGColor];
    line.strokeColor = [[colors objectAtIndex:i] CGColor];
    line.lineWidth = 5;
   // line.contents = (id)[[UIImage imageNamed:@"Mask.png"] CGImage];
   // line.contentsGravity = kCAGravityCenter;



    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 3.0;
    pathAnimation.fromValue = @(0.0f);
    pathAnimation.toValue = @(1.0f);
    pathAnimation.repeatCount = HUGE_VAL;
    [line addAnimation:pathAnimation forKey:@"strokeEnd"];

I have tried adding a contents to the shape layer but I'm bad at animations. The effect I want to achieve is the same animation as "slide to unlock" has, or a path that pulses.

I've tried to do the same thing as the answer from slide-to-unlock but can't seem to manage


Solution

  • I ended up dooing this:

    UIBezierPath *linePath = [UIBezierPath bezierPath];
    [linePath moveToPoint:startPoints];
    [linePath addLineToPoint:endPoints];
    
    //gradient layer for the line
    
    
    CAGradientLayer *gradient = [CAGradientLayer layer];
    gradient.frame = CGRectMake(0, 0, 150.0, 1.0);
    gradient.cornerRadius = 5.0f;
    gradient.startPoint = CGPointMake(0.0, 0.5);
    gradient.endPoint = CGPointMake(1.0, 0.5);
    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor],(id)[[UIColor whiteColor] CGColor],(id)[[UIColor blueColor] CGColor],(id)[[UIColor clearColor] CGColor], nil];
    [scrollViewContent.layer addSublayer:gradient];
    
    
    
    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    anim.path = [linePath CGPath];
    anim.rotationMode = kCAAnimationRotateAuto;
    anim.repeatCount = 0;
    anim.duration = 1;
    [gradient addAnimation:anim forKey:@"gradient"];