Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom gradient background for UIButton?

I would like to create a custom UIButton gradient background. I attached some picture about the requirements.
enter image description here
enter image description here

But my gradient background is not as I expected.

enter image description here

My question is how to set the position or location to the gradient? (from top to center and then center to bottom).

Here is my code:

- (void)setBlueShiningLayer {
    CALayer *buttonLayer = self.layer;
    [buttonLayer setMasksToBounds:YES];
    [buttonLayer setCornerRadius:5.0];
    [buttonLayer setBorderWidth:1.0f];
    [buttonLayer setBorderColor:[UIColor colorWithRed:153.0f / 255.0f green:153.0f / 255.0f blue:153.0f / 255.0f alpha:1.0f].CGColor];

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    [gradientLayer setBounds:self.bounds];
    NSArray *colors = [NSArray arrayWithObjects:
            (id) [UIColor colorWithRed:129.0f / 255.0f green:151.0f / 255.0f blue:179.0f / 255.0f alpha:0.8f].CGColor, // top
            (id) [UIColor colorWithRed:111.0f / 245.0f green:133.0f / 255.0f blue:162.0f / 255.0f alpha:0.4f].CGColor, // center
            (id) [UIColor colorWithRed:95.0f / 245.0f green:118.0f / 255.0f blue:151.0f / 255.0f alpha:0.4f].CGColor, // center
            (id) [UIColor colorWithRed:75.0f / 245.0f green:99.0f / 255.0f blue:133.0f / 255.0f alpha:0.8f].CGColor, // bottom
            nil];

    [gradientLayer setPosition:CGPointMake([self bounds].size.width / 2, [self bounds].size.height / 2)];
    [gradientLayer setColors:colors];
    [buttonLayer insertSublayer:gradientLayer atIndex:0];

    [self setTitleColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f] forState:UIControlStateNormal];
    [self setTintColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.3f]];
}
like image 944
kameny Avatar asked Dec 20 '25 19:12

kameny


1 Answers

It looks like the gradient layer is spacing out the colours evenly. That's why you're getting the effect that you're getting.

To fix this you can use the locations property of CAGradientLayer.

Like this...

gradientLayer.locations = @[@0, @0.5, @0.5, @1.0];

TBH, the easiest way to do this with a UIButton is to use an image.

Just create a button image with the gradient and border that you want and then add it ass the background image.

You can create a resizable image if you need to use it at different sizes.

like image 135
Fogmeister Avatar answered Dec 22 '25 11:12

Fogmeister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!