一、绘制纯色图片
+(UIImage*) createImageWithColor:(UIColor*) color
{
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
二、绘制渐变色图片
/**
* 绘制渐变色的矩形UIImage
*
* @param bounds UIImage的bounds
* @param colors 渐变色数组,可以设置两种颜色
* @param gradientType 渐变的方式:0:水平渐变 1:竖直渐变 2:向下对角线渐变 3:向上对角线渐变
*
* @return 渐变色的UIImage
*/
+ (UIImage*)createGradientRectImageWithBounds:(CGRect)bounds Colors:(NSArray*)colors GradientType:(int)gradientType{
NSMutableArray *cgcolorArr = [NSMutableArray array];
for(UIColor *col in colors) {
[cgcolorArr addObject:(id)col.CGColor];
}
UIGraphicsBeginImageContextWithOptions(bounds.size, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)cgcolorArr, NULL);
CGPoint startPoint = CGPointMake(0.0, 0.0);
if (gradientType == 3) {
startPoint = CGPointMake(0.0, bounds.size.height);
}
CGPoint endPoint = CGPointZero;
switch (gradientType) {
case 0:
endPoint = CGPointMake(bounds.size.width, 0.0);
break;
case 1:
endPoint = CGPointMake(0.0, bounds.size.width);
break;
case 2:
endPoint = CGPointMake(bounds.size.width, bounds.size.height);
break;
case 3:
endPoint = CGPointMake(bounds.size.width, 0.0);
break;
default:
break;
}
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}