项目会遇到给各种UI控件添加渐变背景色的需求,如果只是上下渐变或者左右渐变,可以使用Xcode xcassets
的Slicing功能或者
api
- resizableImageWithCapInsets:
完成功能,但是如果是从左上角到右下角的渐变,或者是右上角到左下角渐变,使用截图恐怕不能完成。下面介绍一种生成渐变颜色UIImage的方法,从而可以使用UIColor的api
+ (UIColor *)colorWithPatternImage:(UIImage *)image
来设置背景色。
首先定义了渐变的类型,如下:
1 2 3 4 5 6
| typedef NS_ENUM(NSUInteger, GradientType) { GradientTypeTopToBottom = 0,//从上到小 GradientTypeLeftToRight = 1,//从左到右 GradientTypeUpleftToLowright = 2,//左上到右下 GradientTypeUprightToLowleft = 3,//右上到左下 };
|
定义接口:
1 2 3 4 5
| @interface UIImage (GradientColor)
+ (UIImage *)gradientColorImageFromColors:(NSArray*)colors gradientType:(GradientType)gradientType imgSize:(CGSize)imgSize;
@end
|
其实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| + (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; }
|
使用方法如下:
1 2 3 4
| UIColor *topleftColor = [UIColor colorWithRed:48/255.0f green:127/255.0f blue:202/255.0f alpha:1.0f]; UIColor *bottomrightColor = [UIColor colorWithRed:35/255.0f green:195/255.0f blue:95/255.0f alpha:1.0f]; UIImage *bgImg = [UIImage gradientColorImageFromColors:@[topleftColor, bottomrightColor] gradientType:GradientTypeUpleftToLowright imgSize:SCREEN_SIZE]; self.view.backgroundColor = [UIColor colorWithPatternImage:bgImg];
|
目前已转行教育行业,欢迎加微信交流:CaryaLiu