簡單畫板
先創建一個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(@"手指離開屏幕");
}