2012-11-23 40 views
0

我使用UIGraphicsGetCurrentContext()爲UI元素創建漸變背景,但我想我誤解了繪圖的發生位置。我希望繪畫在子視圖上進行,但是它發生在視圖本身中。從子視圖獲取CGContextRef

我認爲問題在於當我使用UIGraphicsGetCurrentContext()時,我得到了視圖的CGContextRef,所以這就是繪圖發生的地方。我想要做的是在子視圖上繪製圖形,以便我可以用其他相關子視圖淡入淡出。可以這樣做,還是需要爲背景圖層創建另一個UIView子類?

下面是我正在使用的代碼的簡化,我的目標是能夠淡入和淡出topBar中的背景漸變,同時保持InterfaceControlsView視圖可見。

@implementation InterfaceControlsView 

- (id)initWithFrame:(CGRect)frame 
{ 
    topBar = [[UIView alloc] initWithFrame:CGRectMake(0.0, 20.0, self.frame.size.width, 45.0)]; 
/* etc. */ 
} 

- (void)drawRect:(CGRect)rect { 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGRect rect = topBar.frame; // topBar is a subview 

    CGContextSaveGState(context); 
    CGContextAddRect(context, rect); 
    CGContextClip(context); 
    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0); 
    CGContextRestoreGState(context); 
    /* etc. */ 
} 
@end 

回答

2

要爲子視圖創建漸變bg,您不需要創建子類,使用漸變圖層。 希望這會有所幫助

CALayer *layer = _button.layer; 
layer.borderWidth = 1.0f; 
layer.borderColor = [UIColor lightGrayColor].CGColor; 


CAGradientLayer *gLayer = [CAGradientLayer layer]; 
[gLayer setName:@"gradient"]; 

gLayer.frame = layer.bounds; 

gLayer.colors = [NSArray arrayWithObjects: 
         (id)[UIColor colorWithRed:26.0/255.0 green:94.0/255.0 blue:74.0/255.0 alpha:1.0].CGColor, 
         (id)[UIColor colorWithRed:23.0/255.0 green:59.0/255.0 blue:37.0/255.0 alpha:1.0].CGColor, 
         nil]; 
[layer addSublayer:gLayer]; 
+0

謝謝。比我所做的要容易得多。非常感激。 – Andrew