未完待續(xù)……
Quartz 2D 簡介
Quartz 2D是蘋果公司開發(fā)的一個(gè)二維圖形繪制引擎,同時(shí)支持iOS和Mac系統(tǒng)。
它是一套基于C的API框架,提供了低級(jí)別、輕量級(jí)、高保真度的2D渲染。它能完成的工作有:
- 繪制圖形 : 線條\三角形\矩形\圓\弧等
- 繪制文字
- 繪制\生成圖片(圖像)
- 讀取\生成PDF
- 截圖\裁剪圖片
- 自定義UI控件
- …
Quartz 2D中的坐標(biāo)變換
注意:坐標(biāo)變換操作必須要在添加圖形之前,如果設(shè)置在添加圖形之后的話會(huì)無效。
我們先畫一個(gè)正方形做完參考:
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}

1、平移
func CGContextTranslateCTM(c: CGContext?, _ tx: CGFloat, _ ty: CGFloat)
該方法相當(dāng)于把原來位于 (0, 0) 位置的坐標(biāo)原點(diǎn)平移到 (tx, ty) 點(diǎn)。在平移后的坐標(biāo)系統(tǒng)上繪制圖形時(shí),所有坐標(biāo)點(diǎn)的 X 坐標(biāo)都相當(dāng)于增加了 tx,所有點(diǎn)的 Y 坐標(biāo)都相當(dāng)于增加了 ty。
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextTranslateCTM(context, -50, 25) // 向左向下平移
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}

2、縮放
func CGContextScaleCTM(c: CGContext?, _ sx: CGFloat, _ sy: CGFloat)
該方法控制坐標(biāo)系統(tǒng)在水平方向和垂直方向上進(jìn)行縮放。在縮放后的坐標(biāo)系統(tǒng)上繪制圖形時(shí),所有點(diǎn)的 X 坐標(biāo)都相當(dāng)于乘以 sx 因子,所有點(diǎn)的 Y 坐標(biāo)都相當(dāng)于乘以 sy 因子。
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextScaleCTM(context, 0.5, 1)
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}

3、旋轉(zhuǎn)
func CGContextRotateCTM(c: CGContext?, _ angle: CGFloat)
該方法控制坐標(biāo)系統(tǒng)旋轉(zhuǎn) angle 弧度。在縮放后的坐標(biāo)系統(tǒng)上繪制圖形時(shí),所有坐標(biāo)點(diǎn)的 X、Y 坐標(biāo)都相當(dāng)于旋轉(zhuǎn)了 angle弧度之后的坐標(biāo)。
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextRotateCTM(context, CGFloat(M_PI_4))
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}

注意:旋轉(zhuǎn)的時(shí)候,是整個(gè) layer 都旋轉(zhuǎn)了,所以 layer 看起來應(yīng)該是這樣的:

這個(gè)時(shí)候若想移動(dòng) view ,就應(yīng)該按照這個(gè)旋轉(zhuǎn)過的坐標(biāo)系來移動(dòng):
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, 2.0)
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextRotateCTM(context, CGFloat(M_PI_4))
CGContextTranslateCTM(context, 0, -100) // 在新坐標(biāo)系中向上移動(dòng)100點(diǎn),視圖上看起來像是向右向上都移動(dòng)了
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}
