码迷,mamicode.com
首页 > 其他好文 > 详细

涂鸦画板效果实现

时间:2018-06-04 17:45:54      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:bubuko   void   wpa   github   alt   event   地址   eal   文件   

一个简单的绘图应用,模仿苹果自带软件备忘录里的涂鸦功能

技术分享图片

核心代码

#import "DrawView.h"

#import "DrawPath.h"

@interface DrawView ()

@property (nonatomic, strong) NSMutableArray *paths;


@property (nonatomic, strong) UIBezierPath *path;


@end


@implementation DrawView

- (void)setImage:(UIImage *)image
{
    _image = image;
    
    [self.paths addObject:image];
    

    [self setNeedsDisplay];
}

// 撤销
- (void)undo
{
    [self.paths removeLastObject];
    
    [self setNeedsDisplay];
}
- (void)clear
{
    // 清除画板view所有的路径,并且重绘
    [self.paths removeAllObjects];
    
    [self setNeedsDisplay];
}

- (void)awakeFromNib
{
    _lineWidth = 1;
    _lineColor = [UIColor blackColor];
}

- (NSMutableArray *)paths
{
    if (_paths == nil) {
        _paths = [NSMutableArray array];
    }
    return _paths;
}

// 当手指点击view,就需要记录下起始点
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 获取UITouch
    UITouch *touch = [touches anyObject];
    
    // 获取起始点
    CGPoint curP = [touch locationInView:self];
    
    // 只要一开始触摸控件,设置起始点
    DrawPath *path = [DrawPath path];
    
    path.lineColor = _lineColor;

    [path moveToPoint:curP];

    
    path.lineWidth = _lineWidth;
    
    // 记录当前正在描述的路径
    _path = path;
    
    // 保存当前的路径
    [self.paths addObject:path];
}

// 每次手指移动的时候调用
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

    // 获取UITouch
    UITouch *touch = [touches anyObject];
    
    // 获取当前触摸点
    CGPoint curP = [touch locationInView:self];
    
    [_path addLineToPoint:curP];
    
    // 重绘
    [self setNeedsDisplay];
    
}

// 绘制东西
- (void)drawRect:(CGRect)rect
{
    for (DrawPath *path in self.paths) {
        
        if ([path isKindOfClass:[UIImage class]]) { // 图片
            UIImage *image = (UIImage *)path;
            
            [image drawAtPoint:CGPointZero];
        }else{
            
            [path.lineColor set];
            
            [path stroke];
        }
    }
}



@end

用法很简单,导入DrawView.h  DrawView.m 文件创建该控件即可

清屏:  [_drawView clear];
撤销:  [_drawView undo];
橡皮擦:  _drawView.lineColor = [UIColor whiteColor];

 

github地址:https://github.com/chglog/scrawl

 

涂鸦画板效果实现

标签:bubuko   void   wpa   github   alt   event   地址   eal   文件   

原文地址:https://www.cnblogs.com/chglog/p/9134421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!