Peter Kreinz Peter Kreinz - 2 months ago 39
Swift Question

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

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 for SWIFT!

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

Answer

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!

    }
}

Swift 2

// UIImage+Alpha.swift

import UIKit

extension UIImage{

    func alpha(value:CGFloat)->UIImage
    {
       UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)

       var ctx = UIGraphicsGetCurrentContext();
       let area = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height);

       CGContextScaleCTM(ctx, 1, -1);
       CGContextTranslateCTM(ctx, 0, -area.size.height);  
       CGContextSetBlendMode(ctx, kCGBlendModeMultiply);     
       CGContextSetAlpha(ctx, value);  
       CGContextDrawImage(ctx, area, self.CGImage);

       var newImage = UIGraphicsGetImageFromCurrentImageContext();
       UIGraphicsEndImageContext();

       return newImage;
    }
}

The above new Swift extensions 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%.

Swift 3

let img = UIImage(named: "imageWithoutAlpha")!.alpha(value: 0.5)
let myButton = UIButton()
myButton.setBackgroundImage(img, for: UIControlState.normal)

Swift 2

let img = UIImage(named: "imageWithoutAlpha")!.alpha(0.5)
let myButton = UIButton()
myButton.setBackgroundImage(img, forState: UIControlState.Normal)
Comments