iOS画板

实践做一个小画板

#####鸣谢
从这里作为参考

#####地址

Github地址

#####主要思想
通过

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

三个UIResponder的底层函数来检测手势触点,然后在本地存储下所有触点,然后实时重绘

#####实现


DrawPadView.h

@interface DrawPadView : UIView{
    NSMutableArray *points;
    NSArray *point_all;
    CGContextRef context;
    UIColor *paint_color;
    CGFloat paint_width;
}
@property (strong ,nonatomic) NSMutableArray *points;
@property (strong ,nonatomic) NSArray *points_all;
@property (strong, nonatomic) UIColor *paint_color;
@property (assign, nonatomic) CGFloat paint_width;

@end

DrawPadView.m

其中points_all是用来存储所有触碰过的触点,包括多条路径的不同点

points_all是一个NSArray,数组中存储的对象是多个points对象
每个points对象对应一条完整的路径,是一个NSMutableArray,会在手指触碰屏幕的时候实时添加触点进points

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    _points = [[NSMutableArray alloc] init];
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    [_points addObject:[NSValue valueWithCGPoint:touchPoint]];
}

路径开始点,初始化points数组,并且讲触点添加进数组当中

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSValue *point = [NSValue valueWithCGPoint:[[touches anyObject] locationInView:self]];
   [_points addObject:point];
   [self setNeedsDisplay];
}

然后手指移动的过程中,讲当前时刻的触点存储在points当中

并且实时调用绘制函数 [self setNeedsDisplay]

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSValue *point = [NSValue valueWithCGPoint:[[touches anyObject] locationInView:self]];
   [_points addObject:point];
    NSMutableArray *tempArray = [_points_all mutableCopy];
    [tempArray addObject:_points];
    _points_all = tempArray;
}

然后路径结束的时候,会进入此函数,然后路径结束,讲points添加进points_all

最后是比较重要的重绘函数

- (void)drawRect:(CGRect)rect
{
    if (!_points_all || !_points || [_points count] < 2) 
    {
        _points_all = [[NSArray alloc] init];
        _points = [[NSMutableArray alloc] init];
        return;
    }
    context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, _paint_width);

    CGContextSetStrokeColorWithColor(context, [_paint_color CGColor]);

    //画之前的线
    for (NSArray *array in _points_all){
        [self drawLineWithArray:array];
    }
    //画现在的线
    [self drawLineWithArray:_points];
}

- (void)drawLineWithArray:(NSArray *)array
{
    CGPoint beforePoint = [[array objectAtIndex:0] CGPointValue];
    CGContextMoveToPoint(context, beforePoint.x, beforePoint.y);
    for (UInt64 i = 1; i < [array count]; i++) 
    {
        CGPoint nowPoint = [[array objectAtIndex:i] CGPointValue];
        CGContextAddLineToPoint(context, nowPoint.x, nowPoint.y);
    }
    CGContextStrokePath(context);
}
//根据数组绘制路径

后续会继续做关于颜色改变,粗细设定等方面的开发