2011-06-28 29 views
0

我有以下的UIView自定義類:爲iOS定製梯度BackgroundView不工作

@implementation BackgroundView 

- (void)drawRect:(CGRect)rect 
{ 

    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    CGGradientRef glossGradient; 
    CGColorSpaceRef rgbColorspace; 
    size_t num_locations = 2; 
    CGFloat locations[2] = { 0.0, 1.0 }; 

    float r = (255.0)/(255.0); 
    float g = (165.0)/(255.0); 
    float b = (0.0)/(255.0); 

    float rr = (238.0)/(255.0); 
    float gg = (118.0)/(255.0); 
    float bb = (0.0)/(255.0); 

    CGFloat components[8] = { r, g, b, 1.0, // Start color 
     rr, gg, bb, 1.0 }; // End color 

    rgbColorspace = CGColorSpaceCreateDeviceRGB(); 
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations); 

    CGRect currentBounds = self.bounds; 
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f); 
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)); 
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0); 

    CGGradientRelease(glossGradient); 
    CGColorSpaceRelease(rgbColorspace); 
} 


@end 

基本上,它應該做的橙色漸變。值「r」,「g」和「b」是淺橙色,值「rr」,「gg」,「bb」是深橙色。但它不起作用。只有框架的頂部是橙色,框架的底部是黑色的。我似乎無法擺脫黑色。

我將使用什麼值爲橙色很好的漸變。有人可以尋找錯誤嗎?我找不到任何。非常感謝!

回答

0

那是因爲你指定的結束點的梯度是在currentBounds的中間 - 看到這一行:

CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds)); 

爲了擺脫黑色的確保y座標是在底部你視圖。

或者,您可以使用此代碼終點後,以延長您梯度

CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, kCGGradientDrawsAfterEndLocation);