之前分享过如何画渐变的layer,最近有个需求需要做一个渐变色的导航栏,如果给导航栏画一个渐变的layer的话,不能覆盖到状态栏,所以还是需要使用[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"xxx"] forBarMetrics:UIBarMetricsDefault]
在导航栏的backgroundImageView上想办法。分享一个渲染渐变image的方法
- (UIImage*)imageWithColor:(NSArray *)colors withSize:(CGSize)size{
UIGraphicsBeginImageContextWithOptions(size, YES, 1);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
NSMutableArray *ar = [NSMutableArray array];
for (UIColor *c in colors) {
[ar addObject:(id)c.CGColor];
}
CGColorSpaceRef colorSpace = CGColorGetColorSpace([[colors lastObject] CGColor]);
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)ar, NULL);
CGContextDrawLinearGradient(context, gradient, CGPointMake(0, 0), CGPointMake(size.width, 0), kCGGradientDrawsBeforeStartLocation|kCGGradientDrawsAfterEndLocation);
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
CGGradientRelease(gradient);
CGContextRestoreGState(context);
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return theImage;
}