Search code examples
iosuikitgradientuicolor

How to give horizontal gradient color to button in ios


How to give horizontal gradient color to button in ios?

I am trying to give button gradient color blue in horizontal direction, but not getting output properly.


Solution

  • You can try the below code:

    {
        UIColor *transBgColor = [UIColor colorWithWhite:1.0 alpha:0.0];
        UIColor *black = [UIColor blackColor];
        CAGradientLayer *maskLayer = [CAGradientLayer layer];
        maskLayer.opacity = 0.8;
        maskLayer.colors = [NSArray arrayWithObjects:(id)black.CGColor, 
        (id)transBgColor.CGColor, (id)transBgColor.CGColor, (id)black.CGColor, nil];
    
        // Horizontal - commenting these two lines will make the gradient vertical
        maskLayer.startPoint = CGPointMake(0.0, 0.5);
        maskLayer.endPoint = CGPointMake(1.0, 0.5);
    
        NSNumber *gradTopStart = [NSNumber numberWithFloat:0.0];
        NSNumber *gradTopEnd = [NSNumber numberWithFloat:0.4];
        NSNumber *gradBottomStart = [NSNumber numberWithFloat:0.6];
        NSNumber *gradBottomEnd = [NSNumber numberWithFloat:1.0];
        maskLayer.locations = @[gradTopStart, gradTopEnd, gradBottomStart, gradBottomEnd];
    
        maskLayer.bounds = container.bounds;
        maskLayer.anchorPoint = CGPointZero;
        [container.layer addSublayer:maskLayer];
    }