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

54,355

Solution 1

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)

Solution 2

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)

Solution 3

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)

Solution 4

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

self.imageView.image = UIImageView(image: "image.png")
imageView.alpha = 0.5
Share:
54,355
Peter Kreinz
Author by

Peter Kreinz

Senior Software Engineer - Technical Lead - UI/UX Designer I have a good knowledge of iOS, Swift, SwiftUI, UI/UX Design, Mobile Software Architecture, Core Data, Core Data with CloudKit, In-App Purchase, Auto/Non-renewable Subscriptions, Push Notifications, Augmented Reality (AR), Webservices, RESTful API, OAuth, JWT, PHP, HTML, CSS3, SQL, Node.js, Express.js, Javascript, VanillaJS, jQuery, Objective-C, Arduino, Raspberry PI, ...

Updated on July 09, 2022

Comments

  • Peter Kreinz
    Peter Kreinz almost 2 years

    I found a lot solutions here but not for Swift, and I know you can do this with a UIImageView, but in my case i need an programmatically set alpha transparent background image for an UIButton. Best would be an UIImage extension!

    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 result:

    current

    Desired result:

    desired

  • Peter Kreinz
    Peter Kreinz over 9 years
    sorry, but that makes no sense!
  • leonardo
    leonardo over 9 years
    What exactly doesn't make sense?
  • Peter Kreinz
    Peter Kreinz over 9 years
    I tried your solution, but the transparency/opacity of the background image will not change
  • leonardo
    leonardo over 9 years
    Well, try again because it works 100%. Test properly before downvoting answers.
  • dumbledad
    dumbledad over 8 years
    Not sure why this was down-voted: it proved an easy fix for me.
  • ChucK
    ChucK over 8 years
    In swift 2 I had to replace kCGBlendModeMultiply with CGBlendMode.Multiply, see stackoverflow.com/questions/31309521/…
  • Add080bbA
    Add080bbA over 8 years
    Answer to another question. Question is not "how to change opacity of UIImageView". Question is "how to change alpha of UIImage"
  • Add080bbA
    Add080bbA over 8 years
    Answer to another question. Question is not "how to change opacity of UIImageView". Question is "how to change alpha of UIImage"
  • Patonz
    Patonz over 7 years
    can you post an swift 3 version?
  • Peter Kreinz
    Peter Kreinz over 7 years
    swift 3 version added!
  • Ethan G
    Ethan G over 6 years
    This seems to ignore color. I have an image with colors in it and when I apply this method, the resulting image is gray (but it does have the appropriate alpha).
  • Ethan G
    Ethan G over 6 years
    In reading some of developer.apple.com/library/content/documentation/… it seems like .normal should work fine. Anyone else experiencing this "gray-scale" effect?
  • gondo
    gondo about 4 years
    You are creating imageView but then never using it. You can't set UIView via UIButton.setBackgroundImage.
  • Jan Nash
    Jan Nash about 3 years
    I have to agree with gondo here.