如何以编程方式在SWIFT中设置UIImage的alpha值?

时间:2015-02-14 16:52:16

标签: swift uibutton uiimage uicontrolstate

我在这里找到了很多解决方案,但不是 Swift ,我知道你可以用UIImageView做到这一点,但在我的情况下,我需要一个以编程方式设置alpha透明背景图像的的UIButton 即可。最好的是UIImage扩展!

let img = UIImage(named: "imageWithoutAlpha")
var imgInsets = UIEdgeInsetsMake(0, 24, 0, 24)
image = image!.resizableImageWithCapInsets(imgInsets)

let myButton = UIButton(frame: CGRect(x: 50, y: 50, width: img!.size.width, height: img!.size.height))
myButton.setBackgroundImage(img, forState: UIControlState.Normal)
myButton.contentEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 20)
myButton.setTitle("Startbutton", forState: UIControlState.Normal)
myButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
myButton.sizeToFit()
view.addSubview(myButton)

目前的结果:

current

期望的结果:

desired

4 个答案:

答案 0 :(得分:69)

幸运的是,我能够帮助自己,并希望与您分享我的解决方案:

Swift 3

// UIImage+Alpha.swift

extension UIImage {  

    func alpha(_ value:CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(at: CGPoint.zero, blendMode: .normal, alpha: value)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!   
    }
}

我在项目中添加了上面的新Swift扩展,然后按如下方式更改了UIButton示例,以获得透明度为50%的Alpha透明背景图像。

let img = UIImage(named: "imageWithoutAlpha")!.alpha(0.5)
let myButton = UIButton()

myButton.setBackgroundImage(img, for: .normal)

答案 1 :(得分:22)

最简单的方法是将UIImage放入UIImageView并在那里设置alpha。

let image = UIImage(named: "imageWithoutAlpha")
let imageView = UIImageView(image: image)
imageView.alpha = 0.5

myButton.setBackgroundImage(image, forState: UIControlState.Normal)

答案 2 :(得分:6)

我可以使用以下代码设置alpha:

self.imageView.image = UIImageView(image: "image.png")
imageView.alpha = 0.5

答案 3 :(得分:2)

Swift 5,iOS 10以上版本

如果您的应用不支持iOS 10之前的操作系统,则可以利用功能更强大的UIGraphicsImageRenderer UIKit绘图API。

extension UIImage {
    func withAlpha(_ a: CGFloat) -> UIImage {
        return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { (_) in
            draw(in: CGRect(origin: .zero, size: size), blendMode: .normal, alpha: a)
        }
    }
}

用法

let img = UIImage(named: "someImage")?.withAlpha(0.5)