首先把漸變色實(shí)現(xiàn)之后燕刻,做成一種漸變色圖片
1.先在UIImage里面寫(xiě)一個(gè)類(lèi)擴(kuò)展,具體代碼如下
// .h文件
#import <UIKit/UIKit.h>
typedef NS_ENUM(NSUInteger, GradientType) {
GradientTypeTopToBottom = 0,//從上到小
GradientTypeLeftToRight = 1,//從左到右
GradientTypeUpleftToLowright = 2,//左上到右下
GradientTypeUprightToLowleft = 3,//右上到左下
};
@interface UIImage(GradientColor)
+ (UIImage *)gradientColorImageFromColors:(NSArray*)colors gradientType:(GradientType)gradientType imgSize:(CGSize)imgSize;
@end
// .m文件
#import "UIImage+GradientColor.h"
@implementation UIImage(GradientColor)
+ (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
2.寫(xiě)好類(lèi)擴(kuò)展之后痹籍,在外部這么實(shí)現(xiàn)即可鼎天。具體代碼如下
// 設(shè)置控件背景色(用到了UIImage+GradientColor.h這個(gè)類(lèi)擴(kuò)展)
UIColor *topColor = [UIColor redColor];
UIColor *bottomColor = [UIColor blueColor];
UIImage *bgImg = [UIImage gradientColorImageFromColors:@[topColor, bottomColor] gradientType:GradientTypeTopToBottom imgSize:CGSizeMake(你控件需要的大小)];
[你的控件 setBackgroundColor:[UIColor colorWithPatternImage:bgImg]];