Custom gradient BackgroundView for iOS not working
I have the following UIView custom class:
@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
Basically, it's supposed to make an orange gradient. The values "r", "g", and "b" are for a light orange, and the values "rr", "gg", "bb" are for a dark orange. But it doesn't work. Only the top of the frame i开发者_JAVA百科s orange, and the bottom of the frame is black. I can't seem to get rid of the black.
What values would I use for an orange nice gradient. Can someone please look for mistakes? I can't find any. Thanks so much!
That's because you specify that the end point for your gradient is in middle of the currentBounds - see this line:
CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
To get rid of the black make sure the y coordinate is at the bottom of your view.
Alternatively, you could use this code to extend your gradient after the end point
CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, kCGGradientDrawsAfterEndLocation);
精彩评论