How to set alpha for an assert image in Swift

I just wanted to know how to change the opacity (alpha) of an asset color I have. When I try this UIColor(named: "something", alpha: 0.4), Xcode complains: Extra argument 'alpha' in call.

Is there any way I can modify the opacity of an asset color programmatically?

>Solution :

Use this extension to get the rgb value from the UIColor

extension UIColor {
    var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
        var red: CGFloat = 0
        var green: CGFloat = 0
        var blue: CGFloat = 0
        var alpha: CGFloat = 0
        getRed(&red, green: &green, blue: &blue, alpha: &alpha)

        return (red, green, blue, alpha)

Then you can create a new color

let assetColor = UIColor(named: "something")
let (r,g,b,_) = assetColor.rgba
let newColor = UIColor(red:r, green:g, blue:b, alpha: 0.4)

Leave a Reply