使用:
//107, 140, 174 --- 37, 70, 102
//设置view 背景渐变颜色
UIImage *backImage = [UIImage gradientImageWithBounds:RECT(0, 0, WindowWidth, WindowHeight) andColors:@[RGBCOLOR(107, 140, 174), RGBCOLOR(37, 70, 102)] andGradientType:GradientDirectionTopToBottom];
UIColor *bgColor = [UIColor colorWithPatternImage:backImage];
[self.view setBackgroundColor:bgColor];
CGGradientRef 绘制效果和速度都是比较coreImage好的。
typedef NS_ENUM(NSInteger, GradientDirection) {
GradientDirectionTopToBottom = 0, // 从上往下 渐变
GradientDirectionLeftToRight, // 从左往右
GradientDirectionBottomToTop, // 从下往上
GradientDirectionRightToLeft // 从右往左
};
/**
* @brief 生成渐变色图片
*
* @param bounds 图片的大小
* @param colors 渐变颜色组
* @param gradientType 渐变方向
*
* @return 图片
*/
+ (UIImage*)gradientImageWithBounds:(CGRect)bounds andColors:(NSArray*)colors andGradientType:(GradientDirection)gradientType{
NSMutableArray *ar = [NSMutableArray array];
for(UIColor *c in colors) {
[ar addObject:(id)c.CGColor];
}
UIGraphicsBeginImageContextWithOptions(bounds.size, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
CGPoint startPt = CGPointMake(0.0, 0.0);
CGPoint endPt = CGPointMake(0.0, 0.0);
switch (gradientType) {
case GradientDirectionTopToBottom:
startPt= CGPointMake(0.0, 0.0);
endPt= CGPointMake(0.0, bounds.size.height);
break;
case GradientDirectionLeftToRight:
startPt = CGPointMake(0.0, 0.0);
endPt = CGPointMake(bounds.size.width, 0.0);
break;
case GradientDirectionBottomToTop:
startPt = CGPointMake(0.0, bounds.size.height);
endPt = CGPointMake(0.0, 0.0);
break;
case GradientDirectionRightToLeft:
startPt = CGPointMake(bounds.size.width, 0.0);
endPt = CGPointMake(0, 0.0);
break;
}
CGContextDrawLinearGradient(context, gradient, startPt, endPt, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}