主要思路:同过UIPanGestureRecognizer移动手势创建UIBezierPath线条,把线条添加到数组里面,然后重新实现- (void)drawRect:(CGRect)rect,把所有的线条画出来。
主要代码
// 画线的宽度
@property(nonatomic,assign)CGFloat lineWidth;
// 线条颜色
@property(nonatomic,retain)UIColor* pathColor;
// 加载背景图片
@property(nonatomic,strong)UIImage* image;
// 清屏
- (void)clear;
// 撤销
- (void)undo;
// 橡皮擦
- (void)eraser;
// 保存
- (void)save;
// 重绘UI
- (void)drawRect:(CGRect)rect {
for (DrawBezierPath* path in self.paths) {
if ([path isKindOfClass:[UIImage class]]) {
// 画图片
UIImage* image = (UIImage*)path;
[image drawInRect:rect];
}else{
// 设置画笔颜色
[path.pathColor set];
// 绘制
[path stroke];
}
}
}
// 懒加载属性
- (NSMutableArray*)paths{
if (_paths == nil) {
_paths = [NSMutableArray array];
}
return _paths;
}
// 重写image属性
- (void)setImage:(UIImage *)image{
_image = image;
// 将图片加入到线条数组中
[self.paths addObject:image];
[self setNeedsDisplay];
}
#pragma mark - Init
// 初始化
- (void)setUp{
// 添加平移手势
UIPanGestureRecognizer* panGes = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGes:)];
[self addGestureRecognizer:panGes];
// 默认值
self.lineWidth = 1;
self.pathColor = [UIColor blackColor];
}
#pragma mark - Event
// 平移事件
- (void)panGes:(UIPanGestureRecognizer*)ges{
// 获取当前点
CGPoint curPoint = [ges locationInView:self];
if (ges.state == UIGestureRecognizerStateBegan) { // 开始移动
// 创建贝塞尔曲线
_bezierPath = [[DrawBezierPath alloc] init];
// 设置线条宽度
_bezierPath.lineWidth = _lineWidth;
// 线条默认颜色
_bezierPath.pathColor = _pathColor;
// 设置起始点
[_bezierPath moveToPoint:curPoint];
[self.paths addObject:_bezierPath];
}
// 连线
[_bezierPath addLineToPoint:curPoint];
// 重绘
[self setNeedsDisplay];
}
#pragma mark - Method
// 清屏
- (void)clear{
[self.paths removeAllObjects];
[self setNeedsDisplay];
}
// 撤销
- (void)undo{
[self.paths removeLastObject];
[self setNeedsDisplay];
}
// 橡皮擦
- (void)eraser{
self.pathColor = [UIColor whiteColor];
[self setNeedsDisplay];
}
// 保存
- (void)save{
// ---- 截图操作
// 开启上下文
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0);
// 获取当前上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 渲染图层到上下文
[self.layer renderInContext:context];
// 从上下文中获取图片
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();
// ---- 保存图片
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
网友评论