How to set the alpha of an UIImage in SWIFT programmatically?

I was able to set the alpha using the following code:

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

Luckily I was able to help myself and would like to share with you my solution:

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!   
    }
}

The above new Swift extension I added to my project and then I changed the UIButton example as follows, to have an alpha transparent background image with a transparency of 50%.

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

myButton.setBackgroundImage(img, for: .normal)

The easiest way is to put your UIImage inside a UIImageView and set the alpha there.

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

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

Swift 5, iOS 10+

If your app doesn't support operating systems prior to iOS 10 then you can take advantage of the more robust UIGraphicsImageRenderer UIKit drawing 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)
        }
    }
}

Usage

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