涂鸦画板效果实现

Posted 球哥-chg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了涂鸦画板效果实现相关的知识,希望对你有一定的参考价值。

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

核心代码

#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

 

以上是关于涂鸦画板效果实现的主要内容,如果未能解决你的问题,请参考以下文章

自定义view实现涂鸦(画板)功能

自定义view实现涂鸦(画板)功能

iOS之UI--涂鸦画板实例

自定义view实现涂鸦(画板)功能

DrawBoard 是一个自定义 View 实现的画板;方便对图片进行各种编辑或涂鸦相关操作

自定义view实现涂鸦(画板)功能