导航条渐变色

  • (void)viewDidLoad {
    [super viewDidLoad];
    [self updateNavigationBarBGColor];
    self.title = @"导航title";
    }

//设置导航条的背景为渐变色

  • (void)updateNavigationBarBGColor
    {
    CALayer * bgLayer = [self gradientBGLayerForBounds:CGRectMake(0, 0, self.navigationController.navigationBar.frame.size.width, self.navigationController.navigationBar.frame.size.height)];
    UIGraphicsBeginImageContext(bgLayer.bounds.size);
    [bgLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * bgAsImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if (bgAsImage != nil)
    {
    [self.navigationController.navigationBar setBackgroundImage:bgAsImage forBarMetrics:UIBarMetricsDefault];
    }
    else
    {
    NSLog(@"Failded to create gradient bg image, user will see standard tint color gradient.");
    }
    }

  • (CALayer *)gradientBGLayerForBounds:(CGRect)bounds
    {
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = @[(__bridge id)[UIColor redColor].CGColor, (__bridge id)[UIColor yellowColor].CGColor];
    gradientLayer.locations = @[@0, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1.0, 0);
    gradientLayer.frame = bounds;
    return gradientLayer;
    }

参考原文https://www.jianshu.com/p/6aee372beff2

你可能感兴趣的:(导航条渐变色)