How do you change UIButton image alpha on disabled state?

后端 未结 11 2412
庸人自扰
庸人自扰 2021-02-03 23:22

I have a UIButton with an image and on its disabled state, this image should have .3 alpha.

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIIm         


        
11条回答
  •  一个人的身影
    2021-02-03 23:57

    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];
    

提交回复
热议问题