之前有写过一篇iOS使用贝塞尔曲线创建简易画板,可以跟这篇做一个对比。
依然是先看效果:
画板.gif
原理跟iOS使用贝塞尔曲线创建简易画板中介绍的基本相同,不做详细说明了,直接上主要代码:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint beginPoint = [touch locationInView:touch.view];
NSMutableArray *subarray = [NSMutableArray array];
[subarray addObject:[NSValue valueWithCGPoint:beginPoint]];
[self.totalPathPoints addObject:subarray];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self drawLineWithTouches:touches];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[self drawLineWithTouches:touches];
}
- (void)drawLineWithTouches:(NSSet *)touches {
UITouch *touch = [touches anyObject];
CGPoint movePoint = [touch locationInView:touch.view];
NSMutableArray *subarray = [self.totalPathPoints lastObject];
[subarray addObject:[NSValue valueWithCGPoint:movePoint]];
[self setNeedsDisplay];
}
在drawRect方法当中:
CGContextRef ctx = UIGraphicsGetCurrentContext();
for (NSMutableArray *arr in self.totalPathPoints) {
for (int i = 0; i < arr.count; i++) {
if (i == 0) {
CGPoint startPoint = [arr[i] CGPointValue];
CGContextMoveToPoint(ctx, startPoint.x, startPoint.y);
}
else{
CGPoint movePoint = [arr[i] CGPointValue];
CGContextAddLineToPoint(ctx, movePoint.x, movePoint.y);
}
}
}
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineWidth(ctx, 5);
CGContextStrokePath(ctx);
这里放上demo
网友评论