iOS 中简单实现贪吃蛇动画连线。
更多技术文章请关注我的微博: http://weibo.com/u/2822867275
---------------------------
以下代码以连线的方式实现贪吃蛇的动画,只要给它一个点的数组,
就可以从开始点连线到结束点。
#import <QuartzCore/QuartzCore.h>
@interface CALayer (Animation)
-(void)drawLineWithPoints: (NSArray*)points;
@end
------
#import "CALayer+Animation.h"
@implementation CALayer (Animation)
//animate to draw a line from the point array
-(void)drawLineWithPoints: (NSArray*)points
{
//make sure we have at least 2 points
if (points.count <2)
{
return;
}
//create the path with the points
UIBezierPath *path = [UIBezierPath bezierPath];
//move to the start point
NSValue *firstPointValue = [points objectAtIndex: 0];
CGPoint firstPoint = [firstPointValue CGPointValue];
[path moveToPoint: firstPoint];
//add lines for additional points
for (NSUInteger pointIndex = 1; pointIndex< points.count; pointIndex++)
{
NSValue *pointValue = [points objectAtIndex: pointIndex];
CGPoint currentPoint = [pointValue CGPointValue] ;
[path addLineToPoint: currentPoint];
}
//for line dash
NSNumber *dashLength = [NSNumber numberWithInteger:5];
//create the shap layer
CAShapeLayer *pathLayer = [CAShapeLayer layer];
[pathLayer setValue:@"LinePathLayer" forKey:@"LinePathLayerID" ];
pathLayer.frame = self.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor whiteColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 1.0f;
pathLayer.lineJoin = kCALineJoinMiter;
pathLayer.lineDashPattern = [NSArray arrayWithObjects: dashLength,dashLength, nil];
[self addSublayer: pathLayer];
//add animation to the shap layer
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
pathAnimation.duration = 2.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
//add animation to the layer
[pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];
}
@end
------
如何调用:
CGPoint pStart = CGPointMake( 10.0f, 10.0f);
CGPoint pMiddle = CGPointMake( 10.0f, 200.0f);
CGPoint pEnd = CGPointMake(200.0f, 200.0f);
NSArray *points = [NSArray arrayWithObjects:
[NSValue valueWithCGPoint:pStart],
[NSValue valueWithCGPoint:pMiddle],
[NSValue valueWithCGPoint:pEnd],nil];
// ‘self’ is a class of UIViewController
[self.view.layer drawLineWithPoints: points];