首页 > 代码库 > 画板例子实现

画板例子实现

画板例子思路

步骤一:自定义一个画板视图
步骤二:监听手指触摸事件,当手指在视图滑动的时候,就画线.
2.1在手指开始触摸的时候,创建可变路径,并且设置路径起始点。
- (
void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:
self];
    SUNBezierPath *path = [SUNBezierPath bezierPathWithWidth:_width andWithColor:_color andWithPoint:point];
    _pathU = path;
    [
self.arrayM addObject:path];
   
}

2.2.当手指移动的时候,给路径添加目标点,并且重新绘制视图。
- (
void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:
self];
    [_pathU addLineToPoint:point];
   
// 重绘
   
 [self setNeedsDisplay];
}

2.3 当手指触摸结束,将路径保存起来,并释放当前路径
- (
void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_pathM addObject:_pathU];
    CGPathRelease(_pathU.CGPath);
    NSLog(
@"%s",__func__);
}
注意:
1. [self setNeedsDisplay];这段代码不能少,否则在画板画不出东西。
2.当画板与slider绑定时,要通过awakeFromNib设置线宽,不然线宽默认为0.
- (void)awakeFromNib
{
   
_width = 2;
}
步骤三:实现绘制视图方法
3.1. 自定义路径类
+ (
instancetype)bezierPathWithWidth:(CGFloat)width andWithColor:(UIColor *)color andWithPoint:(CGPoint)point
{
    SUNBezierPath *path = [[SUNBezierPath alloc] init];
    path.lineWidth = width;
    path.color = color;
    [path moveToPoint:point];
   
return path;
}

3.2.实现绘图方法
- (
void)drawRect:(CGRect)rect
{
   
for (SUNBezierPath *pathin self.arrayM) {
       
if ([path isKindOfClass:[UIImage class]])  {
            UIImage *image = (UIImage *)path;
            [image drawAtPoint:CGPointZero];
        }
else{
            [path.color set];
            [path stroke];
        }
    }

步骤四、在storyboard中定义工具栏
4.1 清屏
- (void)clearScreen
{
    [
self.arrayMremoveAllObjects];
    [
selfsetNeedsDisplay];
}
直接把数组removeAllObjects
4.2 撤销
- (void)undo
{
    [
self.arrayMremoveLastObject];
    [
selfsetNeedsDisplay];
}

4.3 保存
- (IBAction)save:(id)sender
{
   
// 截屏
   
// 开启上下文
   
UIGraphicsBeginImageContextWithOptions(_drawingView.bounds.size,NO, 0.0);
   
   
// 获得当前上下文
   
CGContextRef ctr =UIGraphicsGetCurrentContext();
   
// 把画板上的内容渲染都上下文
    [
_drawingView.layerrenderInContext:ctr];
   
   
UIImage *newImage =UIGraphicsGetImageFromCurrentImageContext();
   
   
// 关闭上下文
   
UIGraphicsEndImageContext();
   
   
// 保存到相册里面
   
UIImageWriteToSavedPhotosAlbum(newImage,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
}
调用MBProgressHUD 第三方框架
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
   
if (error) {//保存失败
        [
MBProgressHUDshowError:@"保存失败"];
    }
else{//保存成功
        [
MBProgressHUDshowSuccess:@"保存成功"];
    }
}

4.4 照片
- (IBAction)selectedPicture:(id)sender
{
   
// 去用户的操作
   
UIImagePickerController *picker = [[UIImagePickerControlleralloc]init];
   
    picker.
sourceType= UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [
selfpresentViewController:pickeranimated:YEScompletion:nil];
    picker.
delegate= self;

}

- (
void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
   
NSLog(@"%@",info);
   
UIImage *newImage = info[UIImagePickerControllerOriginalImage];
   
SUNHandleView *handleV = [[SUNHandleViewalloc]initWithFrame:self.drawingView.frame];
    handleV.
delegate= self;
    handleV.
image= newImage;
    [
self.viewaddSubview:handleV];
    [
selfdismissViewControllerAnimated:YEScompletion:nil];

}
注意:去模拟器用户的相册要遵守UIImagePickerControllerDelegate协议,实现
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
以modal的形式
[self presentViewController:picker animated:YES completion:nil];
关闭当初Modal出来的控制器
[self dismissViewControllerAnimated:YES completion:nil];

步骤五、实现从相处里面选择一张图片能够用手势操作。

添加手势
- (
void)addGestureRecognizer
{
   
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizeralloc]initWithTarget:selfaction:@selector(pan:)];
    pan.
delegate= self;
    [
_imageViewaddGestureRecognizer:pan];
   
   
UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizeralloc]initWithTarget:selfaction:@selector(rotation:)];
    rotation.
delegate= self;
    [
_imageViewaddGestureRecognizer:rotation];
   
   
UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizeralloc]initWithTarget:selfaction:@selector(pinch:)];
    pinch.
delegate= self;
    [
_imageViewaddGestureRecognizer:pinch];
   
   
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizeralloc]initWithTarget:selfaction:@selector(longPress:)];
    longPress.
delegate= self;
    [
_imageViewaddGestureRecognizer:longPress];
}

- (
void)pan:(UIPanGestureRecognizer*)pan
{
   
CGPoint point = [pantranslationInView:self];
   
_imageView.transform= CGAffineTransformTranslate(_imageView.transform, point.x, point.y);
    [pan
setTranslation:CGPointZeroinView:_imageView];
}

- (
void)rotation:(UIRotationGestureRecognizer*)rotation
{
   
_imageView.transform= CGAffineTransformRotate(_imageView.transform, rotation.rotation);
    rotation.
rotation= 0;
}

- (
void)pinch:(UIPinchGestureRecognizer*)pinch
{
   
_imageView.transform= CGAffineTransformScale(_imageView.transform, pinch.scale, pinch.scale);
    pinch.
scale= 1;
}

实现长按的操作
- (
void)longPress:(UILongPressGestureRecognizer*)longPress
{
   
if (longPress.state== UIGestureRecognizerStateEnded) {
        [
UIViewanimateWithDuration:0.5animations:^{
           
_imageView.alpha= 0.3;
        }
completion:^(BOOLfinished) {
            [
UIViewanimateWithDuration:0.5animations:^{
               
_imageView.alpha= 1;
            }
completion:^(BOOLfinished) {
               
// 截屏
               
UIGraphicsBeginImageContextWithOptions(self.bounds.size,NO, 0.0);
               
CGContextRef ctr =UIGraphicsGetCurrentContext();
                [
self.layerrenderInContext:ctr];
               
UIImage *image =UIGraphicsGetImageFromCurrentImageContext();
               
NSData *data =http://www.mamicode.com/UIImagePNGRepresentation(image);
                [data
writeToFile:@"/Users/sunjinshuai/Desktop/image.png"atomically:YES];
               
UIGraphicsEndImageContext();
               
UIImageWriteToSavedPhotosAlbum(image,self, @selector(image:didFinishSavingWithError:contextInfo:),nil);
               
// 把图片传给控制器
               
if ([self.delegaterespondsToSelector:@selector(handleView:withImage:)]) {
                    [
self.delegatehandleView:selfwithImage:image];
                }
               
// 从父控件中移除
                [
selfremoveFromSuperview];
            }];
        }];
       
    }
}

- (
void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
   
if (error) {
        [
MBProgressHUDshowError:@"保存失败"];
    }
else{
        [
MBProgressHUDshowSuccess:@"保存成功"];
    }
}

- (
BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
{
   
return YES;
}

- (
void)setImage:(UIImage*)image
{
   
_image = image;
   
_imageView.image= image;
}

- (
void)addImageView
{
   
UIImageView *imageV = [[UIImageViewalloc]initWithFrame:self.bounds];
    imageV.
userInteractionEnabled= YES;
   
_imageView = imageV;
    [
selfaddSubview:imageV];
}

画板例子实现