我们已经学习完了Quartz2D的一些基本的用法,在实际开发过程中,经常使用Quartz2D,可以帮助我们少使用苹果自带的控件,直接画图到上下文,对系统的性能是一个非常好的优化方式。Quartz2D的功能强大,绝逼不是画线,绘制图片那么easy,今天讲一下他在实际项目中的应用,顺便将思路理清楚,方便大家看涂鸦板demo,还有手势解锁
文章中的几个demo
- 1.使用图形上下文制作涂鸦板
- 2.使用贝塞尔路径制作涂鸦板
- 3.手势解锁
下面详细的介绍一下项目的思路
一.使用图形上下文制作涂鸦板
分析
1.涂鸦板实际上就是绘制很多的线条
2.保存线条,使用可变数组
3.使用上下文绘制图片,使用drawRect方法
4.和屏幕交互,应该使用touchesBegin方法
代码分析
1.自定义一个DBPainterView
2.在view中生成一个可变数组作为变量,懒加载处理,可以供程序使用
1 2 3 4 5 |
//MARK: - 懒加载属性 //用于盛放所有单个路径的数组 private lazy var pointArr:NSMutableArray = { return NSMutableArray() }() |
3.实现touchesBegin,touchesMoved,touchesEnd方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//MARK: - 重写touch三个方法 //touchBegin override func touchesBegan(touches: Set, withEvent event: UIEvent?) { let touch = touches.first let startPoint = touch?.locationInView(touch?.view) let linePathArr = NSMutableArray() linePathArr.addObject(NSValue.init(CGPoint: startPoint!)) pointArr.addObject(linePathArr) setNeedsDisplay() } //touchMoved override func touchesMoved(touches: Set, withEvent event: UIEvent?) { let touch = touches.first let startPoint = touch?.locationInView(touch?.view) let lastLineArr = pointArr.lastObject lastLineArr!.addObject(NSValue.init(CGPoint: startPoint!)) setNeedsDisplay() } //touchEnd override func touchesEnded(touches: Set, withEvent event: UIEvent?) { let touch = touches.first let startPoint = touch?.locationInView(touch?.view) let lastLineArr = pointArr.lastObject lastLineArr!.addObject(NSValue.init(CGPoint: startPoint!)) setNeedsDisplay() } |
代码分析,
3.1.touchesBegin
就是开始绘制,现在没有拿到路径的具体的点,所以我们应该给每一个路劲用一个小数组保存所有点的数组 linePathArr(保存每一根line的数组),每一次调用都应该是创建一个新的路径(新的linePathArr),然后加到保存所有路径的数组中( pointArr保存了所有line的数组),然后调用setNeedsDisplay
方法,绘制路径
3.2.touchesMoved
方法是手指在屏幕移动的时候调用的,频率最高,就是一直在添加point,说白了,就是给最新添加的那个路径添加点,所以应当找到数组中最后一个路径,然后给这个路径添加point,let lastLineArr = pointArr.lastObject
,lastLineArr!.addObject(NSValue.init(CGPoint: startPoint!))
3.3.touchEnd
方法和2的事情是一样的,所以可以提炼一下代码,我就不写了
4.绘制图片 drawRect
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
override func drawRect(rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() for index in 0 ..< pointArr.count { //获取单根线 let linePathArr = pointArr.objectAtIndex(index) for j in 0 ..< linePathArr.count { let point = linePathArr.objectAtIndex(j).CGPointValue() if j == 0 { CGContextMoveToPoint(ctx, point.x, point.y) }else .y) }else وeasy,今天讲一下他在实际项目中的应用,顺便将思路理清楚,方便大家看涂鸦板demo,还有手势解锁
一.使用图形上下文制作涂鸦板效果图
代码分析
代码分析,
|