[ios]quartz2d画板功功能实现核心代码

//触摸开始

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    

//    1,获取对应的touch对象

    UITouch *touch = [touches anyObject];

//    2,通过touch对象获取手指触摸对象

    CGPoint startPoint = [touch locationInView:touch.view];

//    3,创建小数组,保存当前路径所有点

    NSMutableArray *subPoints = [NSMutableArray array];

//    4,手指触摸对象起点存于数组

    [subPoints addObject:[NSValue valueWithCGPoint:startPoint]];

//    5,小数组存入大数组

    [self.totalPoints addObject:subPoints];

}

//移动

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    //    1,获取对应的touch对象

    UITouch *touch = [touches anyObject];

    //    2,通过touch对象获取手指触摸对象

    CGPoint movePoint = [touch locationInView:touch.view];

    //    3,从大数组中取出当前路径对应的小数组

    NSMutableArray *subPoints = [self.totalPoints lastObject];

    //    4,手指触摸对象起点存于数组

    [subPoints addObject:[NSValue valueWithCGPoint:movePoint]];

    //    5,调用drawRect方法重回视图

    [self setNeedsDisplay];

 

}

//触摸结束

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self touchesMoved:touches withEvent:event];

}

//画图

- (void)drawRect:(CGRect)rect {

//    1.获取图形上下文

    CGContextRef ctx = UIGraphicsGetCurrentContext();

//    2.遍历大数组取出小数组

    for(NSMutableArray *subPointArray in self.totalPoints)

    {

        for (int index = 0 ; index < subPointArray.count ; index++)

        {

//            3.1取出小数组

            CGPoint point = [subPointArray[index] CGPointValue];

//            3.2绘制线段

            if(0 == index){

//                绘制起点

                CGContextMoveToPoint(ctx, point.x, point.y);

            }else{

//                绘制终点

                CGContextAddLineToPoint(ctx, point.x, point.y);

            }

        }

    }

    CGContextSetLineCap(ctx, kCGLineCapRound);

    CGContextSetLineJoin(ctx, kCGLineJoinRound);

    CGContextSetLineWidth(ctx, 10);

//    渲染

    CGContextStrokePath(ctx);

    

}

//  清屏

-(void)clean

{

    [self.totalPoints removeAllObjects];

    [self setNeedsDisplay];

}

//  撤销

-(void)back

{

    [self.totalPoints removeLastObject];

    [self setNeedsDisplay];

}

 

posted @ 2015-11-18 10:38  suilin  阅读(225)  评论(0编辑  收藏  举报