什么是Quartz2D?
Quartz 2D是一个二维绘图引擎,同时支持iOS和Mac系统
Quartz 2D能完成的工作
- 绘制图形 : 线条\三角形\矩形\圆\弧等
- 绘制文字
- 绘制\生成图片(图像)
- 读取\生成PDF
- 截图\裁剪图片
- 自定义UI控件
Quartz2D在iOS开发中的价值
iOS中,大部分控件都是Quartz2D绘制出来的
- 绘制一些系统UIKit框架中不好展示的内容,例如饼图
- 自定义一些控件
- 不添加UI控件的情况下,使UI内容更丰富
- …..
View内部有个layer(图层)属性,drawRect:方法中取得的是一个Layer Graphics Context,因此,绘制的东西其实是绘制到view的layer上去了
常用方法
CGPathAddLineToPoint
这个方法主要是画一条线 但是必须指定起点
1 2 3
| CGPathMoveToPoint(path, &transform, 100, 50); CGPathAddLineToPoint(path, &transform, 100, 100);
|
上面&transform其实就是指定参照点坐标,为空时相当于(0,0)
第一行是指定线的起点 为(100,50)
第二行就是向(100,100)画线
CGPathAddArc
这个方法是画一条弧线
1
| CGPathAddArc(path, &transform, x1, y1, r, CGFloat(M_PI), 2*CGFloat(M_PI), false);
|
就是以&transform为参照点 以(x1,y1)为中心点 r为半径 从PI到2PI 顺时针(false) 画半圆
CGPathAddArcToPoint
这个是画一条线附带弧线
这个方法相比前两个理解起来稍难
可以看这个解释
1 2
| CGPathMoveToPoint(path, &transform, x1, y1); CGPathAddArcToPoint(path, &transform, x2, y2, x3, y3, r);
|
这样理解 起始点为(x1,y1) 终点为(x3,y3)交叉点为(x2,y2) 画一个半径为r的半圆
注意声称的线只有起始点到交叉处形成的弧线 不包含弧线到终点的部分
示例
吃豆人形状
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 31 32 33 34 35
| func test01(){ UIGraphicsBeginImageContext(self.view.bounds.size); let gc = UIGraphicsGetCurrentContext(); var transform = CGAffineTransformMakeTranslation(0,0); let path = CGPathCreateMutable(); CGPathAddArc(path, &transform, 100, 100, 50, 0, 1.5*CGFloat(M_PI), false); CGPathAddLineToPoint(path, &transform, 100, 100); CGPathAddLineToPoint(path, &transform, 150, 100); CGPathMoveToPoint(path, &transform, 100, 50); CGContextAddPath(gc, path); UIColor.grayColor().setFill(); UIColor.orangeColor().setStroke(); CGContextSetLineWidth(gc, 1); CGContextDrawPath(gc, CGPathDrawingMode.FillStroke); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let imageView = UIImageView(image: image); self.view.addSubview(imageView); }
|
漏斗状
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 31
| func test02(){ UIGraphicsBeginImageContext(self.view.bounds.size); let gc = UIGraphicsGetCurrentContext(); var transform = CGAffineTransformMakeTranslation(50,100); let path = CGPathCreateMutable(); CGPathMoveToPoint(path, &transform, 0, 0); CGPathAddArcToPoint(path, &transform, 50, 200, 100, 0, 10); CGPathAddLineToPoint(path, &transform, 100, 0); CGContextAddPath(gc, path); UIColor.grayColor().setFill(); UIColor.orangeColor().setStroke(); CGContextSetLineWidth(gc, 1); CGContextDrawPath(gc, CGPathDrawingMode.FillStroke); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let imageView = UIImageView(image: image); self.view.addSubview(imageView); }
|