首先打开xcode创建项目,然后自定义view
做ios开发,就是要让在哪做的事情,就归谁管,所以画图方法,和粒子效果都写在自定义的VcView中,而控制器上两个按钮,也只是调用其中的方法罢了:
在viewController.m中
#import "ViewController.h"
#import "VcView.h"
@interface ViewController ()
@property (strong, nonatomic) IBOutlet VcView *ContentV;
@end
@implementation ViewController
- (IBAction)start:(id)sender {
[self.ContentV start];
}
- (IBAction)stop:(id)sender {
[self.ContentV stop];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
在VcView.h中
#import <UIKit/UIKit.h>
@interface VcView : UIView
- (void)start;
- (void)stop;
@end
在VcViem.m中
#import "VcView.h"
@interface VcView ()
@property (nonatomic,strong)UIBezierPath *path;
@property (weak, nonatomic) CALayer *dotlayer;
@end
@implementation VcView
+ (Class)layerClass
{
return [CAReplicatorLayer class];
}
- (void)awakeFromNib
{
//添加手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];
//创建路径
UIBezierPath *path = [UIBezierPath bezierPath];
self.path = path;
//创建粒子
CALayer *layer = [CALayer layer];
layer.frame = CGRectMake(-10, 0, 10, 10);
layer.backgroundColor = [UIColor blackColor].CGColor;
self.dotlayer = layer;
[self.layer addSublayer:layer];
CAReplicatorLayer *reaL = (CAReplicatorLayer *)self.layer;
reaL.instanceCount = 20;
reaL.instanceDelay = 0.25;
}
//开始
-(void)start
{
//添加动画
CAKeyframeAnimation *anim = [CAKeyframeAnimation animation];
anim.keyPath = @"position";
anim.path = self.path.CGPath;
anim.repeatCount = MAXFLOAT;
anim.autoreverses = YES;
[self.dotlayer addAnimation:anim forKey:nil];
}
//重绘
- (void)stop
{
//把路径清空
[self.path removeAllPoints];
[self setNeedsDisplay];
//移除动画
[self.dotlayer removeAllAnimations];
}
- (void)pan:(UIPanGestureRecognizer *)pan
{
//开始绘制
//获取手指当前的点
CGPoint pot = [pan locationInView:self];
if (pan.state == UIGestureRecognizerStateBegan) {
[self.path moveToPoint:pot];
}else if (pan.state == UIGestureRecognizerStateEnded)
{
[self.path addLineToPoint:pot];
[self setNeedsDisplay];
}
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
[self.path stroke];
}
@end
效果图如下