目前实现的画板功能,大部分都是继承于UIView的,很少有继承于UIImageView。其实实现方式也不难,就是自己手动重绘下。下面直接代码解释。
首先,定义两个点的变量。
CGPoint prePoint;
CGPoint curPoint;
其次,对这两个点初始化。
curPoint = CGPointZero;
prePoint = CGPointZero;
接下来,通过Touch event的几个方法,来记录点的位置。
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event ;
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event ;
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event ;
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event ;
后面,编写绘制方法。
UIGraphicsBeginImageContext( self.frame.size);
[imageToDraw drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextSaveGState(UIGraphicsGetCurrentContext());
CGContextSetShouldAntialias(UIGraphicsGetCurrentContext(), YES);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), fPenSize );
CGContextSetStrokeColorWithColor( UIGraphicsGetCurrentContext() , [ [ UIColor whiteColor ] CGColor]);
CGContextSetFillColorWithColor( UIGraphicsGetCurrentContext() , [ [ UIColor whiteColor ] CGColor]);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1 , 1 , 1 , 1.0);
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,nil, startPoint.x, startPoint.y);
CGPathAddLineToPoint(path,nil, endPoint.x, endPoint.y);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear );
CGContextAddPath(UIGraphicsGetCurrentContext(), path);
CGContextStrokePath(UIGraphicsGetCurrentContext());
imageToDraw = UIGraphicsGetImageFromCurrentImageContext();
CGContextRestoreGState(UIGraphicsGetCurrentContext());
UIGraphicsEndImageContext();
该方法需要在touchesMoved、touchesEnded中调用。这样就实现绘制了。
下面,上图。
最后,放一下我的Demo地址,ImageDrawBoard,欢迎提供宝贵的意见或者建议。