How do you change UIButton image alpha on disabled state?

后端 未结 11 2155
庸人自扰
庸人自扰 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-04 00:01

    A swift 4 version of Steph Sharp's answer:

    extension UIImage {
    
        func translucentImageWithAlpha(alpha: CGFloat) -> UIImage {
    
            UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
            let bounds = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
            self.draw(in: bounds, blendMode: .screen, alpha: alpha)
    
            let translucentImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return translucentImage!
        }
    }
    

    Which you can use like this:

    if let image = self.image(for: .normal) {
        self.setImage(image.translucentImageWithAlpha(alpha: 0.3), for: .disabled)
    }
    

提交回复
热议问题