未完待續……
Quartz 2D 簡介
Quartz 2D是蘋果公司開發的一個二維圖形繪制引擎,同時支持iOS和Mac系統。
它是一套基于C的API框架,提供了低級別、輕量級、高保真度的2D渲染。它能完成的工作有:
- 繪制圖形 : 線條\三角形\矩形\圓\弧等
- 繪制文字
- 繪制\生成圖片(圖像)
- 讀取\生成PDF
- 截圖\裁剪圖片
- 自定義UI控件
- …
Quartz 2D中的坐標變換
注意:坐標變換操作必須要在添加圖形之前,如果設置在添加圖形之后的話會無效。
我們先畫一個正方形做完參考:
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)
}
示例.png
1、平移
func CGContextTranslateCTM(c: CGContext?, _ tx: CGFloat, _ ty: CGFloat)
該方法相當于把原來位于 (0, 0) 位置的坐標原點平移到 (tx, ty) 點。在平移后的坐標系統上繪制圖形時,所有坐標點的 X 坐標都相當于增加了 tx,所有點的 Y 坐標都相當于增加了 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)
該方法控制坐標系統在水平方向和垂直方向上進行縮放。在縮放后的坐標系統上繪制圖形時,所有點的 X 坐標都相當于乘以 sx 因子,所有點的 Y 坐標都相當于乘以 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、旋轉
func CGContextRotateCTM(c: CGContext?, _ angle: CGFloat)
該方法控制坐標系統旋轉 angle 弧度。在縮放后的坐標系統上繪制圖形時,所有坐標點的 X、Y 坐標都相當于旋轉了 angle弧度之后的坐標。
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)
}
旋轉
注意:旋轉的時候,是整個 layer 都旋轉了,所以 layer 看起來應該是這樣的:
示例
這個時候若想移動 view ,就應該按照這個旋轉過的坐標系來移動:
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) // 在新坐標系中向上移動100點,視圖上看起來像是向右向上都移動了
let rectangle = CGRectMake(125, 50, 50, 50)
CGContextAddRect(context, rectangle)
CGContextStrokePath(context)
}
旋轉后平移