Based on Alexey Ishkov's answer, but in Swift
I used an extension of the UIImage class.
Swift 2:
UIImage Extension:
extension UIImage {
func imageWithAlpha(alpha: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
drawAtPoint(CGPointZero, blendMode: .Normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
let image = UIImage(named: "my_image")
let transparentImage = image.imageWithAlpha(0.5)
Swift 3/4/5:
Note that this implementation returns an optional UIImage. This is because in Swift 3 UIGraphicsGetImageFromCurrentImageContext
now returns an optional. This value could be nil if the context is nil or what not created with UIGraphicsBeginImageContext
.
UIImage Extension:
extension UIImage {
func image(alpha: CGFloat) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(at: .zero, blendMode: .normal, alpha: alpha)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
To use:
let image = UIImage(named: "my_image")
let transparentImage = image?.image(alpha: 0.5)