代码如下
@interface JFpaintView ()
@property (nonatomic ,strong)NSMutableArray *totalPathPoints;
@property (nonatomic, strong)NSMutableArray *paths;
@end
@implementation JFpaintView
//清除
-(void)clear{
[self.paths removeAllObjects];
[self setNeedsDisplay];
}
//后退
-(void)back{
[self.paths removeLastObject];
[self setNeedsDisplay];
}
/**
* 懒加载
*
* @return 返回一个路径
*/
-(NSMutableArray *)paths{
if (_paths == nil) {
_paths = [NSMutableArray array];
}
return _paths;
}
-(NSMutableArray *)totalPathPoints{
if (_totalPathPoints == nil) {
_totalPathPoints = [NSMutableArray array];
}return _totalPathPoints;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
//取出遍历所有路径
- (void)drawRect:(CGRect)rect {
for (UIBezierPath *path in self.paths) {
path.lineWidth = 10;
[path stroke];
}
}
/**
* 起点
*
*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//1.获取当前的触摸点
UITouch *touch = [touches anyObject];
CGPoint startPos = [touch locationInView:touch.view] ;
//2.创建一个新的路径
UIBezierPath *currenPath = [UIBezierPath bezierPath];
线条的类型
currenPath.lineCapStyle = kCGLineCapRound;
currenPath.lineJoinStyle = kCGLineJoinRound;
//3.设置起点
[currenPath moveToPoint:startPos];
//4.添加数组到数组中
[self.paths addObject:currenPath];
//5.开始展示
[self setNeedsDisplay];
}
/**
* 连线
*
*/
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint pos = [touch locationInView:touch.view];
UIBezierPath *curentPath = [self.paths lastObject];
[curentPath addLineToPoint:pos];
[self setNeedsDisplay];
}
/**
* 连线
*
*/
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[self touchesMoved:touches withEvent:event];
}
//截屏
+ (instancetype)captureWithView:(UIView *)view
{
// 1.开启上下文
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
// 2.将控制器view的layer渲染到上下文
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
// 3.取出图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 4.结束上下文
UIGraphicsEndImageContext();
return newImage;
}
@end
//保存到相册
- (IBAction)save {
//截屏
UIImage *image = [UIImage captureWithView:self.JFView];
//保存到相册
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {//保存失败
[MBProgressHUD showError:@"保存失败"];
}else{//保存成功
[MBProgressHUD showSuccess:@"保存成功"];
}
}
希望可以帮助到你,有问题可以关注我喔,我们一起coding
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-13 09:03:27