How do you change UIButton image alpha on disabled state? How do you change UIButton image alpha on disabled state? ios ios

How do you change UIButton image alpha on disabled state?


If setting alpha while the button is disabled doesn't work, then just make your disabled image at the alpha value you desire.

Just tested this, you can set the alpha on the UIButton, regardless of state and it works just fine.

self.yourButton.alpha = 0.25;


Credit goes to @bryanmac for his helpful answer. I used his code as a starting point, but found the same thing can be achieved without using a UIImageView.

Here's my solution:

- (UIImage *)translucentImageFromImage:(UIImage *)image withAlpha:(CGFloat)alpha{    CGRect rect = CGRectZero;    rect.size = image.size;    UIGraphicsBeginImageContext(image.size);    [image drawInRect:rect blendMode:kCGBlendModeScreen alpha:alpha];    UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return translucentImage;}

Set the button's background image for disabled state:

UIImage * disabledBgImage = [self translucentImageFromImage:originalBgImage withAlpha:0.5f];[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];

EDIT:

I refined my solution further by creating a category on UIImage with this method:

- (UIImage *)translucentImageWithAlpha:(CGFloat)alpha{    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);    [self drawInRect:bounds blendMode:kCGBlendModeScreen alpha:alpha];    UIImage * translucentImage = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return translucentImage;}

Set the button's background image for disabled state:

UIImage * disabledBgImage = [originalBgImage translucentImageWithAlpha:0.5f];[button setBackgroundImage:disabledBgImage forState:UIControlStateDisabled];


You need two instances of UIImage, one for enabled and one for disabled.

The tough part is for the disabled one, you can't set alpha on UIImage. You need to set it on UIImageView but button doesn't take an UIImageView, it takes a UIImage.

If you really want to do this, you can load the same image into the disabled button state after creating a resultant image from the UIImageView that has the alpha set on it.

UIImageView *uiv = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"];// get resultant UIImage from UIImageViewUIGraphicsBeginImageContext(uiv.image.size);CGRect rect = CGRectMake(0, 0, uiv.image.size.width, uiv.image.size.height);[uiv.image drawInRect:rect blendMode:kCGBlendModeScreen alpha:0.2];  UIImage *disabledArrow = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();[button setImage:disabledArrow forState:UIControlStateDisabled];

That's a lot to go through to get an alpha controlled button image. There might be an easier way but that's all I could find. Hope that helps.