Quartz 2D 小练习 画板

project navigator

project navigatorpng

stoaryBoard

storyBoard

code

ViewController.m

//
//  ViewController.m
//  0607画板
//
//  Created by Kinken_Yuen on 2018/6/7.
//  Copyright © 2018年 Kinken_Yuen. All rights reserved.
//

#import "ViewController.h"
#import "ContextView.h"
#import "TempUIView.h"

@interface ViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate,TempUIViewDelegate>
@property (weak, nonatomic) IBOutlet ContextView *ContextView;

@property(nonatomic,strong)TempUIView *tempUIView;

@end

@implementation ViewController
//清屏
- (IBAction)clear:(id)sender {
    [self.ContextView clear];
}

//撤销
- (IBAction)undo:(id)sender {
    [self.ContextView undo];
}

//擦除
- (IBAction)eraser:(id)sender {
    [self.ContextView eraser];
}

//打开照片
- (IBAction)photo:(id)sender {
    UIImagePickerController *pickC = [[UIImagePickerController alloc] init];
    pickC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    pickC.delegate = self;
    [self presentViewController:pickC animated:YES completion:nil];
}

//选择图片后调用
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *newImage = info[UIImagePickerControllerOriginalImage];
    
    //用一个透明UIView作图片的容器
    TempUIView *tempview = [[TempUIView alloc] initWithFrame:self.ContextView.frame];
    tempview.delegate =self;
    tempview.backgroundColor = [UIColor clearColor];
    tempview.image = newImage;
    self.tempUIView = tempview;
    [self.view addSubview:tempview];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - TempUIViewDelegate
-(void)tempUIView:(TempUIView *)tempUIView withImage:(UIImage *)image{
    self.ContextView.image = image;
}



//保存
- (IBAction)save:(id)sender {
    //开启上下文
    UIGraphicsBeginImageContextWithOptions(self.ContextView.bounds.size, NO, 0);
    //渲染到上下文
    [self.ContextView.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    //取得照片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //关闭上下文
    UIGraphicsEndImageContext();
    
    //保存到系统相册
    //必须实现方法image:didFinishSavingWithError:contextInfo:
    UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

//保存涂鸦成功后执行
- (void)image:(UIImage *)image
didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo{
    
}

//设置线宽
- (IBAction)sliderChanged:(UISlider *)sender {
    [self.ContextView setLineWith:sender];
}

//设置颜色
- (IBAction)setColor:(UIButton *)sender {
    [self.ContextView setLineColor:sender.backgroundColor];
}

- (IBAction)closePhoto:(id)sender {
    [self.tempUIView removeFromSuperview];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

ContextView.m

//
//  ContextView.m
//  0607画板
//
//  Created by Kinken_Yuen on 2018/6/7.
//  Copyright © 2018年 Kinken_Yuen. All rights reserved.
//

#import "ContextView.h"
#import "MyBezierPath.h"

@interface ContextView ()
/*存储当前绘制路径*/
@property(nonatomic,strong)UIBezierPath *path;

/*存储所有绘制路径*/
@property(nonatomic,strong)NSMutableArray *pathArray;

/*设置线宽*/
@property(nonatomic,assign)CGFloat lWith;

/*设置的线条颜色*/
@property(nonatomic,strong)UIColor *lColor;

@end

@implementation ContextView
-(NSMutableArray *)pathArray{
    if (_pathArray == nil) {
        _pathArray = [NSMutableArray array];
    }
    return _pathArray;
}

-(void)awakeFromNib{
    [super awakeFromNib];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:pan];
    self.lWith = 1;
    self.lColor = [UIColor blackColor];
}

-(void)pan:(UIPanGestureRecognizer *)pan{
    CGPoint curP = [pan locationInView:self];
    if (pan.state == UIGestureRecognizerStateBegan){
        MyBezierPath *path = [[MyBezierPath alloc] init];
        [path setLineWidth:self.lWith];
        path.lColor = self.lColor;
        self.path = path;
        [self.pathArray addObject:path];
        [path moveToPoint:curP];
    }else if (pan.state == UIGestureRecognizerStateChanged){
        [self.path addLineToPoint:curP];
         [self setNeedsDisplay];
    }
    
}

-(void)drawRect:(CGRect)rect{
    //绘制所有路径
    for (MyBezierPath *path in self.pathArray) {
        if ([path isKindOfClass:[UIImage class]]) {
            UIImage *image = (UIImage *)path;
            [image drawInRect:self.bounds];
        }else{
            [path.lColor set];
            [path stroke];
        }
    }
}

//清屏
-(void)clear{
    [self.pathArray removeAllObjects];
    [self setNeedsDisplay];
}

//撤销
-(void)undo{
    [self.pathArray removeLastObject];
    [self setNeedsDisplay];
}

//擦除,白色线条覆盖
-(void)eraser{
   self.lColor = [UIColor whiteColor];
}

//设置线宽
-(void)setLineWith:(UISlider *)slider{
    self.lWith = slider.value;
}

//设置线条颜色
-(void)setLineColor:(UIColor *)color{
    self.lColor = color;
}

- (void)setImage:(UIImage *)image{
    _image = image;
    [self.pathArray addObject:image];
    //重绘
    [self setNeedsDisplay];
}

@end


@end

TempUIView.h

//
//  TempUIView.h
//  0607画板
//
//  Created by Kinken_Yuen on 2018/6/8.
//  Copyright © 2018年 Kinken_Yuen. All rights reserved.
//

#import <UIKit/UIKit.h>
@class TempUIView;
@protocol TempUIViewDelegate <NSObject>
-(void)tempUIView:(TempUIView *)tempUIView withImage:(UIImage *)image;

@end

@interface TempUIView : UIView
@property(nonatomic,strong)UIImage *image;

@property(nonatomic,weak)id<TempUIViewDelegate> delegate;

@end

TempUIView.m

//
//  TempUIView.m
//  0607画板
//
//  Created by Kinken_Yuen on 2018/6/8.
//  Copyright © 2018年 Kinken_Yuen. All rights reserved.
//

#import "TempUIView.h"
@interface TempUIView ()
@property(nonatomic,strong)UIImageView *imageV;

@end


@implementation TempUIView
- (UIImageView *)imageV{
    if (_imageV == nil) {
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.frame = self.bounds;
        [self addGesture:imageV];
        [self addSubview:imageV];
        _imageV = imageV;
    }
    return  _imageV;
}

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

-(void)addGesture:(UIImageView *)imageView{
    imageView.userInteractionEnabled = YES;
    //添加手势
    //拖拽
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [imageView addGestureRecognizer:pan];
    
    //缩放
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
    [imageView addGestureRecognizer:pinch];
    
    //旋转
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotation:)];
    [imageView addGestureRecognizer:rotation];
    
    //长按
    UILongPressGestureRecognizer *longP = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longP:)];
    [imageView addGestureRecognizer:longP];
}

-(void)pan:(UIPanGestureRecognizer *)pan{
    CGPoint point = [pan translationInView:pan.view];
    pan.view.transform =CGAffineTransformTranslate(pan.view.transform, point.x, point.y);
    [pan setTranslation:CGPointZero inView:pan.view];
}

-(void)pinch:(UIPinchGestureRecognizer *)pinch{
    pinch.view.transform = CGAffineTransformScale(pinch.view.transform, pinch.scale, pinch.scale);
    [pinch setScale:1];
}

-(void)rotation:(UIRotationGestureRecognizer *)rotation{
    rotation.view.transform = CGAffineTransformRotate(rotation.view.transform, rotation.rotation);
    [rotation setRotation:0];
}

-(void)longP:(UILongPressGestureRecognizer *)longP{
    if (longP.state == UIGestureRecognizerStateBegan) {
        [UIView animateWithDuration:0.2 animations:^{
            self.imageV.alpha = 0;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.2 animations:^{
                self.imageV.alpha = 1;
            }completion:^(BOOL finished) {
                UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
                [self.layer renderInContext:UIGraphicsGetCurrentContext()];
                UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                //代理:将图片传给画板
                if ([self.delegate respondsToSelector:@selector(tempUIView:withImage:)]) {
                    [self.delegate tempUIView:self withImage:newImage];
                }
                [self removeFromSuperview];
            }];
        }];
    }
}

@end


访问系统相册需要加入权限:
info.plist添加Privacy - Photo Library Additions Usage Description,Type 选择 String,Value 中输入你的提示语。
否则运行提示:

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryAddUsageDescription key with a string value explaining to the user how the app uses this data.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容

  • 诗云:“邦畿千里,惟民所止。”诗云:“緡蛮黄鸟,止于丘隅。”子曰:“于止,知其所止,可以人而不如鸟乎?”...
    六年级房廉碧阅读 221评论 0 0
  • 抓住春天的尾巴,在夏天的微风还带着一丝丝凉意时,简与一个叫丁扬的男孩子牵起了手。这不是简的第一次约会,甚至不是她高...
    棠梨小阅读 182评论 0 0
  • 七月,下雨的午后。小镇出奇的冷清,马路上没有人影,偶尔传来几声汽车驶过的声音,渐行渐远,悄无声息。门前的法国梧桐树...
    声雨竹_ff18阅读 517评论 7 6