繪制透明圖層
- 調用CGContextBeginTransparencyLayer開始透明層
- 繪制組合對象
- 調用CGContextEndTransparencyLayer結束透明層
CGContextSetShadowWithColor(context, CGSizeZero, 10, [UIColor yellowColor].CGColor);
CGContextBeginTransparencyLayer(context, NULL);
CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
CGContextFillEllipseInRect(context, CGRectMake(100, 150, 100, 100));
CGContextSetFillColorWithColor(context, [UIColor greenColor].CGColor);
CGContextFillEllipseInRect(context, CGRectMake(150, 100, 100, 100));
CGContextSetFillColorWithColor(context, [UIColor blueColor].CGColor);
CGContextFillEllipseInRect(context, CGRectMake(150, 150, 100, 100));
CGContextEndTransparencyLayer(context);
效果圖1
注意
CGContextSetShadowWithColor一定要在CGContextBeginTransparencyLayer透明層開始之前。
因為CGContextBeginTransparencyLayer與CGContextEndTransparencyLayer之間是一個整體,你可以把整個看做是一個對象,陰影作用在整個對象上面,如果寫在CGContextBeginTransparencyLayer之后,那么就變成內部組合對象每一個都有陰影。 也就是說寫不寫透明層都沒有關系了。 如下圖沒有加透明層或者陰影寫在了透明層內部,可以看到視圖層疊處也有陰影。
效果圖2
原因:
Quartz透明層可以理解為一個對象組,對象組里面又有多個對象。效果都會作用域對象組。Quartz為每一個上下文維護一個透明層棧。可以嵌套。當CGContextEndTransparencyLayer調用后,Quartz講對象放入上下文。并使用上全文的全局alpha值、陰影狀態、剪裁區域作用域對象組。