iOS 中简单实现贪吃蛇动画连线。

伦敦iOS小牛 2014-04-30 05:48:19

更多技术文章请关注我的微博: 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];
...全文
284 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
不担心 2014-04-30
  • 打赏
  • 举报
回复
谢谢楼主分享

29,027

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧