Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the alpha of an 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!

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

like image 969
Peter Kreinz Avatar asked Feb 14 '15 16:02

Peter Kreinz


People also ask

How do I change the opacity of an image in Swift?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

How do I change the UIImage size in Swift?

Show activity on this post. extension UIImage { func imageResize (sizeChange:CGSize)-> UIImage{ let hasAlpha = true let scale: CGFloat = 0.0 // Use scale factor of main screen UIGraphicsBeginImageContextWithOptions(sizeChange, ! hasAlpha, scale) self. draw(in: CGRect(origin: CGPoint.

What is Alpha in Swift?

alpha = 0.5 is that the label will have an opacity of 50% as well, so I figured out that it maybe would be possible to have a UIView with white background color and opacity (white_view), and then have another UIView with the label (label_view).

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


1 Answers

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) 
like image 124
Peter Kreinz Avatar answered Sep 20 '22 12:09

Peter Kreinz