Quartz 2D繪圖只能在UIView中重寫drawRect:方法中進行繪制,其他地方都無效,會報錯。
繪制過程:
1. 獲取上下文 CGContextRef context = UIGraphicsGetCurrentContext();
2. 添加圖形 CGContextAddRect(context , CGRectMake(50, 50, 100, 100));
3. 繪制圖形 CGContextDrawPath(context ,kCGPathEOFill);
4. 關閉上下文 CGContextClosePath(context);
Quartz 2D 坐標系變換
1. CGContextRotateCTM(CGContextRef c, CGFloat angle)方法可以相對原點旋轉上下文坐標系
2. CGContextTranslateCTM(CGContextRef c, CGFloat tx, CGFloat ty)方法可以相對原點平移上下文坐標系
3. CGContextScaleCTM(CGContextRef c, CGFloat sx, CGFloat sy)方法可以縮放上下文坐標系
注意:
轉換坐標系前,使用CGContextSaveGState(CGContextRef c)保存當前上下文狀態
坐標系轉換后,使用CGContextRestoreGState(CGContextRef c)可以恢復之前保存的上下文狀態
Quartz基本繪圖方法
CGContextBeginPath 開始一個新路徑CGContextMoveToPoint 設置路徑的起點CGContextClosePath 關閉路徑CGContextAddPath 添加路徑CGContextAddLineToPoint 在指定點添加線CGContextAddLines 添加多條線CGContextAddRect 添加矩形CGContextAddRects 添加多個矩形CGContextAddEllipseInRect 在矩形區域中添加橢圓CGContextAddArc 添加圓弧CGContextAddArcToPoint 在指定點添加圓弧CGContextAddCurveToPoint 在指定點添加曲線CGContextDrawPath 繪制路徑CGContextFillPath 實心路徑CGContextFillRect 實心矩形CGContextFillRects 多個實心矩形CGContextFillEllipseInRect 在矩形區域中繪制實心橢圓CGContextStrokePath 空心路徑CGContextStrokeRect 空心矩形CGContextStrokeRectWithWidth 使用寬度繪制空心矩形CGContextStrokeEllipseInRect 在矩形區域中繪制空心橢圓CGContextSetLineWidth 設置線寬CGContextSetBlendMode 設置混合模式CGContextSetShouldAntialias 設置抗鋸齒效果CGContextSetLineCap 設置線條收尾點樣式CGContextSetLineJoin 設置線條連接點樣式CGContextSetLineDash 設置虛線
繪制image
1. 獲取圖像上下文 UIGraphicsBeginImageContext(....);
2. 畫圖 CGRect rect = CGRectMake(....);
3. 設置顏色 [[UIColor redColor] set];
4. 填充 UIRectFill(rect);
5. 獲取圖像 UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
6. 關閉上下文 UIGraphicsEndImageContext
繪制PDF
1. 創建PDF上下文 UIGraphicsBeginPDFContextToFile(path, CGRectZero,NULL); path為沙盒路徑;參數2若設為CGRectZero則建立612*792大小的頁面
2. 創建PDF內容,需要分頁設置,方法 UIGraphicsBeginPDFPage 創建一頁。
3. 關閉PDF上下文 UIGraphicsEndPDFContext();
新聞熱點
疑難解答