iOS-生成简单的渐变图片

释放双眼,带上耳机,听听看~!

 

.h
typedef NS_ENUM(NSUInteger, GradientType) {

GradientTypeTopToBottom = 0,//从上到下
GradientTypeLeftToRight = 1,//从左到右
GradientTypeUpleftToLowright = 2,//左上到右下
GradientTypeUprightToLowleft = 3,//右上到左下
};

@interface UIImage (EXtension)

(UIImage *)imageWithColor:(UIColor *)color;
/** 设置图片的渐变色(颜色->图片)

@param colors 渐变颜色数组 @param gradientType 渐变样式 @param imgSize 图片大小 @return 颜色->图片
*/

(UIImage )gradientColorImageFromColors:(NSArray)colors gradientType:(GradientType)gradientType imgSize:(CGSize)imgSize;
@end

.m
import "UIImage+EXtension.h"
@implementation UIImage (EXtension)

//这个方法可以抽取到 UIImage 的分类中

(UIImage *)imageWithColor:(UIColor *)color
{
NSParameterAssert(color != nil);

CGRect rect = CGRectMake(0, 0, 1, 1);
// Create a 1 by 1 pixel context
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
[color setFill];
UIRectFill(rect); // Fill it with your color
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}

(UIImage )gradientColorImageFromColors:(NSArray)colors gradientType:(GradientType)gradientType imgSize:(CGSize)imgSize {
NSMutableArray *ar = [NSMutableArray array];
for(UIColor *c in colors) {
[ar addObject:(id)c.CGColor];
}
UIGraphicsBeginImageContextWithOptions(imgSize, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
CGPoint start;
CGPoint end;
switch (gradientType) {
case GradientTypeTopToBottom:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(0.0, imgSize.height);
break;
case GradientTypeLeftToRight:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(imgSize.width, 0.0);
break;
case GradientTypeUpleftToLowright:
start = CGPointMake(0.0, 0.0);
end = CGPointMake(imgSize.width, imgSize.height);
break;
case GradientTypeUprightToLowleft:
start = CGPointMake(imgSize.width, 0.0);
end = CGPointMake(0.0, imgSize.height);
break;
default:
break;
}
CGContextDrawLinearGradient(context, gradient, start, end,kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return image;
}

@end

 

人已赞赏
iOS文章

iOS cell自定义左滑/侧滑删除(支持iOS11)

2019-12-10 11:46:07

iOS文章

iOS 判断,qq,银行卡,手机号,邮编,生日,数字,字符串,护照, email

2019-12-10 14:28:04

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索