2011-12-28 38 views
1

我創建了一個自定義的進度條,它的子類UIView並實現了drawRect。我設法在整個視圖上繪製一個漸變。然而,我想繪製幾個不同的漸變,每個漸變都處於不同的位置。如何將CGContextDrawLinearGradient限制在我的視圖內的較小矩形?iOS在視圖的一部分繪製漸變

glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations); 
CGPoint topCenter = CGPointMake(start + (CGRectGetMidX(currentBounds)/currentBounds.size.width), 0.0f);` 
     CGPoint midCenter = CGPointMake(start + (CGRectGetMidX(currentBounds)/currentBounds.size.width), currentBounds.size.height); 
     CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0); 
     start = start + (values[i]/currentBounds.size.width); 
     CGGradientRelease(glossGradient); 
    } 

回答

4

您可以使用CGContectClipToRect限制繪圖區域

然後對於每個梯度做:

CGContextSaveGState(currentContext); 
CGContextClipToRect(theRect); // theRect should be the area where you want to draw the gradient 
... // gradient drawing code 
CGContextRestoreGState(currentContext); 
+0

這正是我所缺少的 - 謝謝! – nambar 2011-12-30 06:46:34

3

正如Quartz 2D Programming Guide說:

當你畫一個漸變,填充石英當前上下文。繪製 漸變不同於處理顏色和圖案,其中 用於描邊和填充路徑對象。因此,如果您希望 您的漸變顯示爲特定的形狀,則需要相應地剪裁 上下文。

既然你想繪製每個梯度在一個矩形,你將要爲每個梯度和矩形做這樣的事情:

CGContextSaveGState(currentContext); { 
    CGContextClipToRect(currentContext, currentBounds); 
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0); 
} CGContextRestoreGState(currentContext);