在 iOS 上用 Core Graphics 繪製圖形時,陰影效果可以透過 CGContextSetShadow 套用到圖形環境上。若需要指定陰影顏色,則改用 CGContextSetShadowWithColor——它的參數與前者完全相同,只是多了一個 CGColorRef 型別的參數用來設定顏色。
-(void)drawRect:(CGRect)rect {
[self drawRectAtTopOfScreen];
// 由於第一個矩形繪製時已套用陰影,第二個矩形即使沒有重設,陰影設定仍然有效
[self drawRectAtBottomOfScreen];
}
- (void)drawRectAtTopOfScreen {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
/*
第二個參數:陰影位移,由 CGSize 指定,從每個圖形要套用陰影的右下部分開始計算。
位移的 x 值越大,圖形右側的陰影擴散得越遠;y 值越大,下方陰影越低。
第三個參數:模糊值,以 CGFloat 指定。給 0.0f 會讓陰影成為實心形狀,數值越大越模糊。
*/
CGContextSetShadowWithColor(currentContext,
CGSizeMake(10.0f, 10.0f),
20.0f,
[[UIColor grayColor] CGColor]);
/* 先建立路徑 */
CGMutablePathRef path = CGPathCreateMutable();
CGRect firstRect = CGRectMake(55.0f, 60.0f, 150.0f, 150.0f);
CGPathAddRect(path, NULL, firstRect);
CGContextAddPath(currentContext, path);
[[UIColor colorWithRed:0.20f green:0.60f blue:0.80f alpha:1.0f] setFill];
CGContextDrawPath(currentContext, kCGPathFill);
CGPathRelease(path);
}
- (void)drawRectAtBottomOfScreen {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGMutablePathRef secondPath = CGPathCreateMutable();
CGRect secondRect = CGRectMake(150.0f, 250.0f, 100.0f, 100.0f);
CGPathAddRect(secondPath, NULL, secondRect);
CGContextAddPath(currentContext, secondPath);
[[UIColor purpleColor] setFill];
CGContextDrawPath(currentContext, kCGPathFill);
CGPathRelease(secondPath);
}
陰影設定是「圖形環境層級」的狀態,一旦套用就會持續生效,直到被再次修改或重設。範例中第二個矩形並沒有重新設定陰影,卻依然帶有陰影,正是這個原因。若希望某個圖形不帶陰影,可在繪製前以 CGContextSaveGState/CGContextRestoreGState 隔離狀態,這是 Core Graphics 繪圖時值得養成的好習慣。
另外,使用 CGMutablePathRef 時務必記得 CGPathRelease,尤其在 MRC 環境下,否則容易造成記憶體洩漏。