正常狀況下,在使用CoreGraphics框架中的方法進行圖形繪製時,每一閉合的圖形都是一個獨立的層,若是在繪製時添加了陰影效果,則經過陰影能夠很明顯的看到圖形的分層狀況,後繪製的圖形在上層,先繪製的圖形在下層,示例代碼以下:框架
-(void)drawRect:(CGRect)rect{ float width = rect.size.width/2; CGPoint center = CGPointMake(rect.size.width/2, rect.size.height/2); CGSize myShadowOffset = CGSizeMake (10, -20); CGContextRef myContext = UIGraphicsGetCurrentContext(); //設置陰影 CGContextSetShadow (myContext, myShadowOffset, 10); //繪製三個圓形 CGContextSetRGBFillColor (myContext, 0, 1, 0, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/2, center.y-width/4*3, width, width)); CGContextSetRGBFillColor (myContext, 0, 0, 1, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/4, center.y-width/4, width, width)); CGContextSetRGBFillColor (myContext, 1, 0, 0, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/4*3, center.y-width/4, width, width)); }
運行效果以下圖所示:spa
從圖中能夠發現,所繪製的3個圓形並不是是在同一層級上,有時開發者可能須要繪製邊界複雜的圖形,還以上面的例子來講,若是開發者須要繪製某個圖形的邊界是有3個圓形拼接而成,出現這樣的層級效果是不合理的。CoreGraphics框架中也提供了進行圖形聚合繪製的方法,示例以下:code
-(void)drawRect:(CGRect)rect{ float width = rect.size.width/2; CGPoint center = CGPointMake(rect.size.width/2, rect.size.height/2); CGSize myShadowOffset = CGSizeMake (10, -20); CGContextRef myContext = UIGraphicsGetCurrentContext(); CGContextSetShadow (myContext, myShadowOffset, 10); CGContextBeginTransparencyLayer (myContext, NULL); //開啓圖形聚合繪製 //以後的繪製代碼都將繪製到統一層上 CGContextSetRGBFillColor (myContext, 0, 1, 0, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/2, center.y-width/4*3, width, width)); CGContextSetRGBFillColor (myContext, 0, 0, 1, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/4, center.y-width/4, width, width)); CGContextSetRGBFillColor (myContext, 1, 0, 0, 1); CGContextFillEllipseInRect(myContext, CGRectMake(center.x-width/4*3, center.y-width/4, width, width)); //結束聚合繪製 CGContextEndTransparencyLayer (myContext); }
效果以下圖所示:ip
有了聚合繪製這樣的方法,進行復雜圖形的繪製將更加靈活!開發
專一技術,熱愛生活,交流技術,也作朋友。class
——琿少 QQ羣:203317592iOS開發