1. 繪制一條直線
1.1 ?聲明全局屬性,用來(lái)存放觸摸屏幕時(shí)的初始坐標(biāo)點(diǎn)和路徑
@property (nonatomic,assign) CGPoint locPoint;
@property (nonatomic,strong) UIBezierPath *path;
1.2 在觸摸屏幕事件里
*獲取觸摸對(duì)象
*獲取最初觸摸屏幕時(shí)的點(diǎn)
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
? ? UITouch *touch = touches.anyObject;
? ? CGPoint locPoint = [touch locationInView:touch.view];
? ? self.locPoint = locPoint;
}
1.3 在觸摸屏幕移動(dòng)的事件中
*獲取觸摸對(duì)象
*創(chuàng)建路徑
*獲取在屏幕移動(dòng)時(shí)的坐標(biāo)點(diǎn)
*重繪
說(shuō)明:因?yàn)樵谝苿?dòng)事件中創(chuàng)建路徑,所以一旦手指離開屏幕重新觸摸移動(dòng)就會(huì)重新繪制一條新的直線
- (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];
}
效果:
當(dāng)點(diǎn)擊屏幕不松手后,移動(dòng)位置,繪制出一條從最初觸摸屏幕時(shí)的點(diǎn)到最后停止時(shí)的點(diǎn)的一條直線
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)建使用了一個(gè)懶加載的方式:
- (UIBezierPath *)path{
? ? if (!_path) {
? ? ? ? _path = [UIBezierPath bezierPath];
? ? }
? ? return _path;
}
實(shí)現(xiàn)效果圖:
3.繪制觸摸路徑 代碼和前兩種幾乎一致,同樣只是路徑的創(chuàng)建位置不同,實(shí)現(xiàn)的效果不同而已
3.1 touchesBegan:
不同點(diǎn)在于在這里創(chuàng)建路徑后,賦值給全局路徑屬性,這樣每一次移動(dòng)都在原來(lái)的路徑上追加了一條線,執(zhí)行重繪時(shí),就會(huì)按照觸摸屏幕的軌跡繪制線了
- (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 效果圖: