绘制:
创建DrawView,继承UIView (用C来写) (OC用[]调用,C直接调用,参数放后面)
在ViewController里用代码写的话,会执行此方法;直接在Storyboardl 里把View的Class设置为DrawView的话不执行initWithFrame方法,执行initWithCode 转下
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
}
return self;
}
//当通过sb或xib创建控件的时候会调用此 初始化方法
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) {
self.points = [NSMutableArray array];
}
return self;
}
//此方法第一次显示出来的时候,会自动调用一次,之后每次执行setNeeddisplay(设置需要显示)方法的时候会执行
//设置画笔来画线
-(void)drawRect:(CGRect)rect{
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//设直线的颜色
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
//把画笔移到某一位置
CGContextMoveToPoint(context, 20, 200);
//添加一条线到某点
CGContextAddLineToPoint(context, 120, 300);
CGContextAddLineToPoint(context, 220, 100);
//绘制
CGContextDrawPath(context , kCGPathStroke);
}
//设置画笔来画线
-(void)drawRect:(CGRect)rect{
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
//设直线的颜色
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
for (int i; i<self.points.count; i++) { //遍历每一个点
CGPoint p = [self.points[i] CGPointValue];
if (i ==0) {
CGContextMoveToPoint(context, p.x, p.y); //把画笔移到某点
}else{
CGContextAddLineToPoint(context, p.x, p.y); //添加一条线到某点
}
}
//绘制
CGContextDrawPath(context , kCGPathStroke);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self];
[self.points addObject:[NSValue valueWithCGPoint:p]];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self];
[self.points addObject:[NSValue valueWithCGPoint:p]];
[self setNeedsDisplay];
}