实现代码如下:
①在自定义视图中定义3个属性
//记录线条的路径
@property (nonatomic, retain) NSMutableArray *paths;
//设置绘图过程中线条的颜色
@property (nonatomic, retain) UIColor *pathColor;
@property (nonatomic, assign) CGFloat pathWidth;
//撤销功能
- (void)undo;
//清除功能
- (void)clear;
②实现效果,需要在手指开始移动即移动过程中处理操作,即需要在下面两个方法中操作.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
方法中实现:
//实现相应时间
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//获取手指对象
UITouch *touch = [touches anyObject];
//获取手指当前触摸点
CGPoint startPoint = [touch locationInView:touch.view];
//创建路径对象
UIBezierPath *path = [UIBezierPath bezierPath];
//设置路径的起始点
[path moveToPoint:startPoint];
//配置路径属性
//线条宽度
path.lineWidth = self.pathWidth;
//线条结合处样式
path.lineJoinStyle = kCGLineJoinRound;
//线条样式
path.lineCapStyle = kCGLineCapRound;
//将路径添加到路径数组中
[self.paths addObject:path];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
//获取手指对象
UITouch *touch = [touches anyObject];
//获取手指当前触摸的位置
CGPoint currentPoint = [touch locationInView:touch.view];
//获得当前路径
UIBezierPath *path = [self.paths lastObject];
//设置路径终点
[path addLineToPoint:currentPoint];
//该方法无需实现,只是通过它自动调用drawRect方法
[self setNeedsDisplay];
}
③实现视图中自带方法(drawRect),代码如下:
- (void)drawRect:(CGRect)rect {
[self.pathColor setStroke];
//遍历所有路径
for (UIBezierPath *path in self.paths) {
path.usesEvenOddFillRule = YES;
[self.pathColor setFill];
//设置笔画的颜色
[self.pathColor setStroke];
//和所有的路径相连
[path stroke];
}
}
④属性实现懒加载 即实现消除 和撤销操作
- (NSMutableArray *)paths {
if (!_paths) {
self.paths = [NSMutableArray arrayWithCapacity:1];
}
return [[_paths retain] autorelease];
}
- (CGFloat)pathWidth {
if (!_pathWidth) {
_pathWidth = 1;
}
return _pathWidth;
}
//撤销功能
- (void)undo {
//删除最后一条数据,路径
[self.paths removeLastObject];
[self setNeedsDisplay];
}
//清除功能
- (void)clear {
//删除所有信息
[self.paths removeAllObjects];
[self setNeedsDisplay];
}
④实现将涂鸦图片保存到系统相册.
1)获取涂鸦图片(UIImage的分类方法),view即当前涂鸦的视图
+ (UIImage *)saveImageFromDrawView:(UIView *)view {
//获取图形上下文(上下文在这两个Graphics之间有效或者在DracRect中有效)
UIGraphicsBeginImageContext(view.frame.size);
//2.将要保存的view的layer绘制到bitmap图形上下文中,完成拍照的功能
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
//从当前上下文获取图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//结束操作
UIGraphicsEndImageContext();
return image;
2)将图片保存(写在button的触发事件中)
//获取要保存的图片
UIImage *image = [UIImage saveImageFromDrawView:self.nameView];
//保存到相册
UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
⑤滑动最下方的滑竿实现改变线条颜色,即线条的宽度.
//设置颜色
- (IBAction)colorAction:(UISlider *)sender {
//CGFloat value = sender.value;
self.nameView.pathColor = [UIColor colorWithHue:sender.value saturation:sender.value brightness:sender.value alpha:sender.value];
}
//设置线条的宽度
- (IBAction)boldAction:(UISlider *)sender {
self.nameView.pathWidth = sender.value;
}
原文:http://blog.csdn.net/zfx5130/article/details/43537771