0

Anyone know how to/if it's a good idea to animate CGPaths in a UIView's drawRect method?

For example, draw a black line from one end of the UIView to the other and then as a timer ticks over, change each individual pixel to a different colour variation to imitate a colour 'flow' of sorts (think Mexican wave, but with colour shades).

Is this doable/efficient?

Cœur
  • 37,241
  • 25
  • 195
  • 267
blindman457
  • 293
  • 1
  • 11
  • I think yes its doable, check for some stuffs like this http://stackoverflow.com/questions/10869509/how-to-animate-a-uibezierpath a combination of `CAAnimation` and `UIBezierPath`. – iphonic Jun 19 '14 at 12:45
  • It should be quite simple. One way would be to use a CAShapeLayer have it's path set to a UIBezierPath for which you could then use a CABasicAnimation to set the strokeStart and StrokeEnd – MDB983 Jun 19 '14 at 13:44

1 Answers1

0

Try this.

-(void)drawRect:(CGRect)rect{
[UIView animateWithDuration:0.5 animations:^{
    CAShapeLayer *shapeLayer=[CAShapeLayer layer];
shapeLayer.path=[self maskPath].CGPath;
[yourview.layer setMask:shapeLayer];
}

-(UIBezierPath *)maskPath{
UIBezierPath *path=[[UIBezierPath alloc] init];
[path moveToPoint:[self normalizedCGPointInView:yourview ForX:1 Y:1]];
[path addLineToPoint:[self normalizedCGPointInView:yourview ForX:9 Y:1]];
[path addLineToPoint:[self normalizedCGPointInView:yourview ForX:9 Y:9]];
[path addLineToPoint:[self normalizedCGPointInView:yourview ForX:1 Y:9]];

return path;
}

-(CGPoint)normalizedCGPointInView:(UIView *)view ForX:(CGFloat)x Y:(CGFloat)y{
CGFloat normalizedXUnit=view.frame.size.width/10;
CGFloat normalizedYUnit=view.frame.size.height/10;
return CGPointMake(normalizedXUnit*x, normalizedYUnit*y);
}

By using a normalised co-ordinate scheme it's a lot easier to calculate the BezierPath for the mask. Additionally it means that the mask is always relative to the size of your view and not fixed to a specific size.

Hope this helps!

Sadiq Jaffer
  • 500
  • 2
  • 10