简单画板
先创建一个UIView 名字AppView
重写initWithFrame方法:
-(id)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
//UIView的背景颜色
self.backgroundColor = [UIColor whiteColor];
//是否可以交互
self.userInteractionEnabled = YES;
//是否允许多个手指
self.multipleTouchEnabled = YES;
linesArray = [NSMutableArray array];
}
return self;
}
然后在本类的drawRect:
- (void)drawRect:(CGRect)rect {
//拿到画板
CGContextRef context = UIGraphicsGetCurrentContext();
//设置画笔粗细和颜色
CGContextSetLineWidth(context, 5);
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:34/255.0 green:199/255.0 blue:1.0 alpha:1].CGColor);
for (int i = 0; i < linesArray.count; i++)
{
NSArray *pointsArray = linesArray[i];
//拿到第一个点
CGContextMoveToPoint(context, [pointsArray[0] CGPointValue].x, [pointsArray[0] CGPointValue].y);
for (int j = 1; j< pointsArray.count; j++)
{
//对剩下坐标每个坐标进行绘画
CGContextAddLineToPoint(context, [pointsArray[j] CGPointValue].x, [pointsArray[j] CGPointValue].y);
}
}
//绘画
CGContextStrokePath(context);
}
添加手势:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"手指放在上面");
//的到手指开始坐标
points = [NSMutableArray array];
UITouch *touch = touches.anyObject;
CGPoint point = [touch locationInView:self];
[pointArray addObject:[NSValue valueWithCGPoint:point]];
//把开始坐标放进数组 pointArray为全局变量NSMutableArray
[linesArray addObject:pointArray];
NSLog(@"%lu",(unsigned long)linesArray.count);
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"手指移动");
//的到手指坐标
UITouch *touch = touches.anyObject;
CGPoint point = [touch locationInView:self];
//大数组嵌套小数组的方法
[pointArray addObject:[NSValue valueWithCGPoint:point]];
//调用drawRect方法 重新绘画
[self setNeedsDisplay];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSLog(@"手指离开屏幕");
}