#import <UIKit/UIKit.h>
@interface XView : UIView
@property (nonatomic, strong) NSMutableArray *lineArray;//保存每条线
@end
//继承于UIView
画板的底板View
#import "XView.h"
@implementation XView
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_lineArray = [NSMutableArray array];
}
return self;
}
/*重新绘图*/
- (void)drawRect:(CGRect)rect {
//获取当前上下文 相当于coreData的contentText
CGContextRef context = UIGraphicsGetCurrentContext();
//设置画笔的颜色
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
//设置线的宽度
CGContextSetLineWidth(context, 3);
//点连线
for (int i = 0; i < _lineArray.count; i++) {
//取出每条线
NSMutableArray *array = _lineArray[i];
for (int j = 0; j < array.count-1; j++) {//防止数组越界
//取出每个开始点 取出每条线的二个点 ***绘图:把画笔移动到开始点 2点进行连线 提交连线
NSValue *v1 = array[j];
NSValue *v2 = array[j+1];
CGPoint p1 = [v1 CGPointValue];
CGPoint p2 = [v2 CGPointValue];
//把画笔移动到开始点
CGContextMoveToPoint(context, p1.x, p1.y);
CGContextAddLineToPoint(context, p2.x, p2.y);
CGContextStrokePath(context);
}
}
}
//获取开始点 bigArray 保存每条线 smallArray 每个点
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//1. 获取手指信息
UITouch *touch = [touches anyObject];
//2. 获取点
CGPoint p1 = [touch locationInView:self];
//3. 把点转换成对象类型
NSValue *value1 = [NSValue valueWithCGPoint:p1];
//4. 点放进小数组
NSMutableArray *smallArray = [NSMutableArray array];
[smallArray addObject:value1];
//5. 再放到大数组
[_lineArray addObject:smallArray];
}
//获取每一个点 加到对应的数组里面
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint p2 = [touch locationInView:self];
//3. 把点转换成对象类型
NSValue *value2 = [NSValue valueWithCGPoint:p2];
//4. 点放进小数组
NSMutableArray *smallArray2 = [_lineArray lastObject];
[smallArray2 addObject:value2];
//5.调用drawRect绘图
[self setNeedsDisplay];//重新绘制一遍
}
@end