自定义渐变BackgroundView for iOS无法正常工作

时间:2011-06-28 16:22:59

标签: iphone ios uiview gradient

我有以下UIView自定义类:

@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"是一个深橙色。但它不起作用。只有框架的顶部是橙色,框架的底部是黑色。我似乎无法摆脱黑色。

我将使用橙色漂亮渐变的值。有人可以找错吗?我找不到任何东西。非常感谢!

1 个答案:

答案 0 :(得分:0)

那是因为您指定渐变的终点位于currentBounds的中间位置 - 请参阅以下行:

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

要消除黑色,请确保y坐标位于视图的底部。

或者,您可以使用此代码在结束点之后扩展渐变

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