源码下载地址:http://download.csdn.net/detail/liu537192/8546721
效果图同ios-day17-02
核心代码除了JLPaintView.m,其他的都与ios-day17-02一样,下面附上JLPaintView.m的代码:
//
// JLPaintView.m
// 02-涂鸦
//
// Created by XinYou on 15-3-30.
// Copyright (c) 2015年 vxinyou. All rights reserved.
//
#import "JLPaintView.h"
@interface JLPaintView()
/**
* 可变数组,用于存储所有的路径(每一条线表示一个路径)
*/
@property (nonatomic, strong)NSMutableArray *allPaths;
@end
@implementation JLPaintView
- (void)clear{
// 清空存储所有路径的数组
[self.allPaths removeAllObjects];
// 重绘(刷新)
[self setNeedsDisplay];
}
- (void)back{
// 删除最后一条路径
[self.allPaths removeLastObject];
// 重绘(刷新)
[self setNeedsDisplay];
}
- (NSMutableArray *)allPaths{
if (_allPaths == nil) {
_allPaths = [NSMutableArray array];
}
return _allPaths;
}
/**
* 手指刚接触屏幕时调用
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
// 确定起点
CGPoint startPoint = [touch locationInView:touch.view];
// 每一次开始触摸,创建一个新的路径
UIBezierPath *path = [UIBezierPath bezierPath];
// 设置线段头尾的样式
path.lineCapStyle = kCGLineCapRound;
// 设置线段转折点的样式
path.lineJoinStyle = kCGLineJoinRound;
// 设置起点
[path moveToPoint:startPoint];
// 把本次的路径(path)添加到allPaths中
[self.allPaths addObject:path];
// 重绘(刷新)
[self setNeedsDisplay];
}
/**
* 手指在屏幕上移动时会调用
*/
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
// 当前移动到了哪个点(当前点)
CGPoint currentPoint = [touch locationInView:touch.view];
// 取出本次路径
UIBezierPath *path = [self.allPaths lastObject];
// 连线
[path addLineToPoint:currentPoint];
// 重绘(刷新)
[self setNeedsDisplay];
}
/**
* 手指离开屏幕时会调用
*/
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[self touchesMoved:touches withEvent:event];
}
- (void)drawRect:(CGRect)rect{
// 设置颜色
[[UIColor blackColor] set];
for (UIBezierPath *path in self.allPaths) {
// 设置线宽(也可以在创建UIBezierPath对象的时候设置)
path.lineWidth = 2;
// 渲染
[path stroke];
}
}
@end