如图所示:
image.png
实现将橙、红两色从左到右渐变,生成一张尺寸为(200,100)的图片。
调用示例为:
UIImage *image = [UIImage imageFromGradientColors:@[UIColor.redColor,UIColor.orangeColor] gradientType:GradientTypeLeftToRight imageSize:CGSizeMake(200, 100)];
self.imageView.image = image;
分类实现完整代码为:
UIImage+newImage.h
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, GradientType) {
GradientTypeTopToBottom = 0,//从上到小
GradientTypeLeftToRight = 1,//从左到右
GradientTypeUpleftToLowright = 2,//左上到右下
GradientTypeUprightToLowleft = 3,//右上到左下
};
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (newImage)
/**
通过渐变色生成图片
@param colors 渐变颜色数组
@param gradientType 渐变类型
@param imageSize 需要的图片尺寸
*/
+ (UIImage *)imageFromGradientColors:(NSArray *)colors gradientType:(GradientType)gradientType imageSize:(CGSize)imageSize;
@end
NS_ASSUME_NONNULL_END
UIImage+newImage.m
#import "UIImage+newImage.h"
@implementation UIImage (newImage)
+ (UIImage *)imageFromGradientColors:(NSArray *)colors gradientType:(GradientType)gradientType imageSize:(CGSize)imageSize {
NSMutableArray *array = [NSMutableArray array];
for(UIColor *color in colors) {
[array addObject:(id)color.CGColor];
}
array = (NSMutableArray *)[[array reverseObjectEnumerator] allObjects];
UIGraphicsBeginImageContextWithOptions(imageSize, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)array, NULL);
CGPoint start;
CGPoint end;
switch (gradientType) {
case GradientTypeTopToBottom:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(0.0, imageSize.height);
break;
case GradientTypeLeftToRight:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(imageSize.width, 0.0);
break;
case GradientTypeUpleftToLowright:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(imageSize.width, imageSize.height);
break;
case GradientTypeUprightToLowleft:
start = CGPointMake(imageSize.width, 0.0);
end = CGPointMake(0.0, imageSize.height);
break;
default:
break;
}
CGContextScaleCTM(context,1.0, -1.0);
CGContextTranslateCTM(context,0, -imageSize.height);
CGContextDrawLinearGradient(context, gradient, start, end, 0);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}
@end
指定单一颜色,生成图片:
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
CGRect rect = CGRectMake(0, 0, size.width, size.height);
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}