#define UIColorFromRGB( R, G, B ) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0]
void drawLinearGradient( CGContextRef context, CGRect rect, NSArray *colors, BOOL vertical )
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
{
//CGFloat locations[] = { 0.0, 0.5 , 1.0};
CGGradientRef gradient = CGGradientCreateWithColors( colorSpace, (__bridge CFArrayRef)colors, nil );
{
CGPoint startPoint = vertical ? CGPointMake( CGRectGetMinX( rect ), CGRectGetMinY( rect ) ) : CGPointMake( CGRectGetMinX( rect ), CGRectGetMinY( rect ) );
CGPoint endPoint = vertical ? CGPointMake( CGRectGetMaxX( rect ), CGRectGetMinY( rect ) ) : CGPointMake( CGRectGetMinX( rect ), CGRectGetMaxY( rect ) );
CGContextDrawLinearGradient( context, gradient, startPoint, endPoint, 0 );
}
CGGradientRelease( gradient );
}
CGColorSpaceRelease( colorSpace );
}
UIImage *
createGradientImage( CGSize size, NSArray *colors, BOOL vertical )
{
UIImage *image = nil;
UIGraphicsBeginImageContext( size );
{
CGContextRef context = UIGraphicsGetCurrentContext();
// push context to make it current (need to do this manually because we are not drawing in a UIView)
UIGraphicsPushContext(context);
{
drawLinearGradient( context, CGRectMake( 0, 0, size.width, size.height ), colors, vertical );
}
UIGraphicsPopContext();
image = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
return( image );
}
CGSize screenSize = [UIScreen mainScreen].bounds.size;
CGFloat scale = [UIScreen mainScreen].scale;
UIImage *backgroundImage = createGradientImage( CGSizeMake( screenSize.width * scale, screenSize.height * scale ),
@[(id)[UIColorFromRGB( 0, 0, 0 ) CGColor], (id)[UIColorFromRGB( 255, 0, 0 ) CGColor], (id)[UIColorFromRGB( 0, 255, 0 ) CGColor] ],
NO );
UIImageView * backgroundView = [[UIImageView alloc] initWithImage:backgroundImage];
backgroundView.frame = CGRectMake(0, 0, screenSize.width, screenSize.height);
[self.view addSubview:backgroundView];