2011-07-14 42 views

回答

16

添加當前上下文的路徑,該路徑定義所需的形狀並在繪製之前剪切上下文。示例代碼:

- (void)drawRect:(CGRect)rect 
{ 
    CGPoint c = self.center ; 
    // Drawing code 
    CGContextRef cx = UIGraphicsGetCurrentContext(); 

    CGContextSaveGState(cx); 
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); 

    CGFloat comps[] = {1.0,1.0,0.0,1.0,0.0,1.0,0.0,1.0}; 
    CGFloat locs[] = {0,1}; 
    CGGradientRef g = CGGradientCreateWithColorComponents(space, comps, locs, 2); 


    CGMutablePathRef path = CGPathCreateMutable(); 
    CGPathMoveToPoint(path, NULL, c.x, c.y); 
    CGPathAddLineToPoint(path, NULL, c.x, c.y-100); 
    CGPathAddArcToPoint(path, NULL, c.x+100, c.y-100, c.x+100, c.y, 100); 
    CGPathAddLineToPoint(path, NULL, c.x, c.y); 

    CGContextAddPath(cx, path); 
    CGContextClip(cx); 

    CGContextDrawRadialGradient(cx, g, c, 1.0f, c, 320.0f, 0); 

    CGContextRestoreGState(cx); 
    ... // Do some more drawing may be 
} 
+0

嗨Vladimar,這是一個偉大的繪畫。 – NSFeaster

+0

嗨弗拉迪瑪,這是一幅很棒的畫。我需要幫助繪製一個類似的漸變,但在一個矩形內。我有一個矩形區域,它是黑色的,我需要一個灰色來從UIView的中心徑向發起。我會非常感謝你的幫助。 – NSFeaster

+0

@Shukaku,我不確定,但不會裁剪你的矩形區域的工作? – Vladimir