1. 繪制一條直線
1.1 ?聲明全局屬性,用來存放觸摸屏幕時的初始坐標點和路徑
@property (nonatomic,assign) CGPoint locPoint;
@property (nonatomic,strong) UIBezierPath *path;
1.2 在觸摸屏幕事件里
*獲取觸摸對象
*獲取最初觸摸屏幕時的點
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? CGPoint locPoint = [touch locationInView:touch.view];
? ? self.locPoint = locPoint;
}
1.3 在觸摸屏幕移動的事件中
*獲取觸摸對象
*創(chuàng)建路徑
*獲取在屏幕移動時的坐標點
*重繪
說明:因為在移動事件中創(chuàng)建路徑,所以一旦手指離開屏幕重新觸摸移動就會重新繪制一條新的直線
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? UIBezierPath *path = [UIBezierPath bezierPath];
? ? [path moveToPoint:self.locPoint];
? ? CGPoint currentPoint = [touch locationInView:touch.view];
? ? [path addLineToPoint:currentPoint];
? ? self.path = path;
? ? [self setNeedsDisplay];
}
1.4 繪制圖形
- (void)drawRect:(CGRect)rect {
? ? [self.path stroke];
}
效果:
當點擊屏幕不松手后,移動位置,繪制出一條從最初觸摸屏幕時的點到最后停止時的點的一條直線
2 ?繪制多條直線
2.1 代碼部分基本一致,只是路徑的創(chuàng)建位置不同,touchesBegan:
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? CGPoint locPoint = [touch locationInView:touch.view];
? ? self.locPoint = locPoint;
}
2.2 touchesMoved:
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
? ? [self.path moveToPoint:self.locPoint];
? ? UITouch *touch = touches.anyObject;
? ? CGPoint currentPoint = [touch locationInView:touch.view];
? ? [self.path addLineToPoint:currentPoint];
? ? [self setNeedsDisplay];
}
2.3 路徑的創(chuàng)建使用了一個懶加載的方式:
- (UIBezierPath *)path{
? ? if (!_path) {
? ? ? ? _path = [UIBezierPath bezierPath];
? ? }
? ? return _path;
}
實現(xiàn)效果圖:
3.繪制觸摸路徑 代碼和前兩種幾乎一致,同樣只是路徑的創(chuàng)建位置不同,實現(xiàn)的效果不同而已
3.1 touchesBegan:
不同點在于在這里創(chuàng)建路徑后,賦值給全局路徑屬性,這樣每一次移動都在原來的路徑上追加了一條線,執(zhí)行重繪時,就會按照觸摸屏幕的軌跡繪制線了
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? CGPoint locPoint = [touch locationInView:touch.view];
? ? UIBezierPath *path = [[UIBezierPath alloc]init];
? ? [path moveToPoint:locPoint];
? ? self.path = path;
}
3.2 touchesMoved:
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? CGPoint currentPoint = [touch locationInView:touch.view];
? ? [self.path addLineToPoint:currentPoint];
? ? [self setNeedsDisplay];
}
3.3 效果圖: