您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

Quartz 2D 繪圖入門:UIView drawRect、座標轉換與常用 API

編輯:iOS 技巧大全

Quartz 2D 是 iOS 早期常見的繪圖方式,适合作靜態圖形、路徑、矩形、圓形與簡單動畫的底層繪製。若想自訂畫面,通常會在 UIView 子類別中覆寫 drawRect:。

繪圖的基本流程

  1. 取得目前圖形上下文:CGContextRef context = UIGraphicsGetCurrentContext();
  2. 建立路徑或加入圖形,例如 CGContextAddRect。
  3. 使用 CGContextDrawPath、CGContextFillPath 或 CGContextStrokePath 繪製。
  4. 必要時關閉路徑,完成繪圖。
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextAddRect(context, CGRectMake(50, 50, 100, 100));
CGContextDrawPath(context, kCGPathEOFill);
CGContextClosePath(context);

座標系轉換

Quartz 2D 可做平移、旋轉與縮放。轉換前建議先儲存狀態,完成後再恢復,避免影響後續繪圖。

  • CGContextRotateCTM:相對原點旋轉座標系。
  • CGContextTranslateCTM:相對原點平移座標系。
  • CGContextScaleCTM:縮放座標系。
  • CGContextSaveGState:儲存目前上下文狀態。
  • CGContextRestoreGState:恢復先前儲存的狀態。

常用繪圖方法

CGContextBeginPath
CGContextMoveToPoint
CGContextClosePath
CGContextAddLineToPoint
CGContextAddRect
CGContextAddEllipseInRect
CGContextAddArc
CGContextAddCurveToPoint
CGContextDrawPath
CGContextFillRect
CGContextStrokeRect
CGContextSetLineWidth
CGContextSetLineDash

這些 API 能組合出多數基礎介面元素。實際開發時,建議先釐清尺寸與座標,再進行繪製,較容易維持畫面穩定。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved