在上一篇文章中我介绍了 UIBezierPath类 介绍 ,下面这篇文章介绍一下如何通过这个类实现一个简单的随手画画板的简单程序demo,功能包括:划线(可以调整线条粗细,颜色),撤销笔画,回撤笔画,清除画布,橡皮擦。当然也可以扩展其他的功能。
一、首先看看实现划线部分的关键代码吧!
- (void) drawRect: (CGRect) rect
{
//绘制图片
int width = self.pickedImage.size.width;
int height = self.pickedImage.size.height;
CGRect rectForImage = CGRectMake(0,0, width, height);
[self.pickedImage drawInRect:rectForImage];
if (self.arrayStrokes)
{
int arraynum = 0;
// each iteration draw a stroke
// line segments within a single stroke (path) has the same color and line width
for (NSDictionary *dictStroke in self.arrayStrokes)
{
NSArray *arrayPointsInstroke = [dictStroke objectForKey:@"points"];
UIColor *color = [dictStroke objectForKey:@"color"];
float size = [[dictStroke objectForKey:@"size"] floatValue];
[color set]; // Sets the color of subsequent stroke and fill operations to the color that the receiver represents.
// draw the stroke, line by line, with rounded joints
UIBezierPath* pathLines = [UIBezierPath bezierPath];
CGPoint pointStart = CGPointFromString([arrayPointsInstroke objectAtIndex:0]);
[pathLines moveToPoint:pointStart];
for (int i = 0; i < (arrayPointsInstroke.count - 1); i++)
{
CGPoint pointNext = CGPointFromString([arrayPointsInstroke objectAtIndex:i+1]);
[pathLines addLineToPoint:pointNext];
}
pathLines.lineWidth = size;
pathLines.lineJoinStyle = kCGLineJoinRound; //拐角的处理
pathLines.lineCapStyle = kCGLineCapRound; //最后点的处理
[pathLines stroke];
arraynum++;//统计笔画数量
}
}
}
// Start new dictionary for each touch, with points and color
- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
NSMutableArray *arrayPointsInStroke = [NSMutableArray array]; //点数组,相当于一个笔画
NSMutableDictionary *dictStroke = [NSMutableDictionary dictionary];
[dictStroke setObject:arrayPointsInStroke forKey:@"points"];
[dictStroke setObject:self.currentColor forKey:@"color"];
[dictStroke setObject:[NSNumber numberWithFloat:self.currentSize] forKey:@"size"];
CGPoint point = [[touches anyObject] locationInView:self];
[arrayPointsInStroke addObject:NSStringFromCGPoint(point)];
[self.arraySt