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?
CodePudding user response:
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)
CodePudding user response:
You can add this extension for UIColor
and easy to use.
extension UIColor {
convenience init?(named: String, alpha: CGFloat) {
if let rgbComponents = UIColor(named: named)?.cgColor.components {
self.init(red: rgbComponents[0], green: rgbComponents[1], blue: rgbComponents[2], alpha: alpha)
} else {
self.init(named: named)
}
}
}
Usage:
let colorWithAlpha = UIColor(named: "Assets Color", alpha: 0.5)
CodePudding user response:
You can set color alpha component when you assign color as follows:
button.backgroundColor = .black.withAlphaComponent(0.5)
CodePudding user response:
You can modify asset color from here Select that particular asset color and Drag that opacity indicator in left or right or directly set some values
CodePudding user response:
UIColor
, as mentioned by Jasur S., has the withAlphaComponent(_:)
.
It can be used with any UIColor
objects to modify its alpha
:
let color = UIColor(named: "something")?.withAlphaComponent(0.5)
Creating custom extensions to cover existing functionality is an arguable good.