避免设计美工切渐变背景图,增加安装包大小。双色渐变的背景图可以用代码实现(多色渐变也可以实现,本工具类只抽取了双色渐变,可以拓展)。废话不多说,上代码:
工具方法XDShadeTool.h里的方法声明
/**
* 设置指定起止点的渐变图片背景
* imageSize 背景图的size
* bR bG bB 起始颜色RGB
* eR eG bB 终止颜色RGB
* bLocation 起始位置
* eLocation 终止位置
*/
+ (UIImageView *)setupShadeImgWithSize:(CGSize)imageSize beginColorR:(CGFloat)bR bG:(CGFloat)bG bB:(CGFloat)bB endColorR:(CGFloat)eR eG:(CGFloat)eG eB:(CGFloat)eB beginLocation:(CGPoint)bLocation endLocation:(CGPoint)eLocation;
/**
* 设置纵向渐变
* view 要渐变渲染的view
* beginColor 起始颜色
* endColor 终止颜色
*/
+ (void)setupEndlongShadeWithView:(UIView *)view beginColor:(UIColor *)beginColor endColor:(UIColor *)endColor;
工具方法XDShadeTool.m里的方法实现
//设置指定起止点的渐变图片背景
+ (UIImageView *)setupShadeImgWithSize:(CGSize)imageSize beginColorR:(CGFloat)bR bG:(CGFloat)bG bB:(CGFloat)bB endColorR:(CGFloat)eR eG:(CGFloat)eG eB:(CGFloat)eB beginLocation:(CGPoint)bLocation endLocation:(CGPoint)eLocation
{
UIGraphicsBeginImageContext(imageSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();
CGGradientRef myGradient;
int location_num = 2;
CGFloat components[] = {bR/255.0,bG/255.0,bB/255.0,1.0 ,eR/255.0,eG/255.0,eB/255.0,1.0};
CGFloat locations[] = {0.0,1.0};
myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, location_num);
CGContextDrawLinearGradient(context, myGradient, bLocation,eLocation,0); //两个点,前一个表示起点,第二个表示终点
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
return imgView;
}
//设置纵向渐变
+ (void)setupEndlongShadeWithView:(UIView *)view beginColor:(UIColor *)beginColor endColor:(UIColor *)endColor
{
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)beginColor.CGColor, (id)endColor.CGColor, nil];
[view.layer insertSublayer:gradient atIndex:0];
}
具体调用: 导入头文件#import “XDShadeTool.h”
// 自定义起始点的渐变图片背景
UIImageView *bg = [XDShadeTool setupShadeImgWithSize:self.view.bounds.size beginColorR:17 bG:16 bB:200 endColorR:99 eG:11 eB:30 beginLocation:CGPointMake(0, 0) endLocation:CGPointMake(self.view.bounds.size.width, self.view.bounds.size.height)];
[self.view addSubview:bg];
// 自定义颜色纵向渐变背景
[XDShadeTool setupEndlongShadeWithView:self.view beginColor:[UIColor blueColor] endColor:[UIColor orangeColor]];
简单好用,一直都选他