本文說明如何透過 CGAffineTransformMakeScale 建立一個仿射縮放變換,並將它套用到繪製路徑上。
以下為 ZYViewController 的 drawRect 實作範例:
[plain]
- (void)drawRect:(CGRect)rect{
CGMutablePathRef path = CGPathCreateMutable();
CGRect rectangle = CGRectMake(10.0f, 10.0f, 200.0f, 300.0f);
// 將矩形縮放為 0.5 倍
CGAffineTransform transform = CGAffineTransformMakeScale(0.5f, 0.5f);
/* 將矩形加入路徑 */
CGPathAddRect(path, &transform, rectangle);
/* 取得目前的繪圖上下文 */
CGContextRef currentContext = UIGraphicsGetCurrentContext();
/* 將路徑加入上下文 */
CGContextAddPath(currentContext, path);
/* 設定填滿色為矢車菊藍 */
[[UIColor colorWithRed:0.20f green:0.60f blue:0.80f alpha:1.0f] setFill];
/* 設定描邊色為棕色 */
[[UIColor brownColor] setStroke];
/* 設定描邊線寬為 5 */
CGContextSetLineWidth(currentContext, 5.0f);
/* 描邊並填滿路徑 */
CGContextDrawPath(currentContext, kCGPathFillStroke);
/* 釋放路徑 */
CGPathRelease(path);
}
透過將縮放矩陣傳入 CGPathAddRect,就能在繪製時套用縮放效果。