I would like to replace a color by another in my UITabBar when it is selected. The aim is to get one image that I can change the colors programmatically.
How can I do it?
let tabBarItem = UITabBarItem(title: menuName, image: unselectedImage, selectedImage: selectedImage)
I faced the same kind of problem. You should create a background white png, and put the other image on top with a translucent background png.
(And I think that you should use image with better quality because your pics look weird)
let iconWhite: UIImage? = self.load(fileName: "APP/icones/\(iconName).png")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
//UNSELECT IMAGE
var unselectedImgBack = UIImage(named: "white.png")
var unselectedImgFront = iconWhite?.overlayImage(color: UIColor.black)
let size = unselectedImgFront?.size
unselectedImgBack = unselectedImgBack?.resized(to: size!)
UIGraphicsBeginImageContext(size!)
let areaSize = CGRect(x: 0, y: 0, width: size!.width, height: size!.height)
unselectedImgBack!.draw(in: areaSize)
unselectedImgFront!.draw(in: areaSize, blendMode: .normal, alpha: 1)
unselectedImgFront = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let unselectedImage = unselectedImgFront!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
//SELECT IMAGE
var selectedImgBack = UIImage(named: "white.png")
var selectedImgFront = iconWhite
let scanner2 = Scanner(string: color)
var value: UInt64 = 0
if scanner2.scanHexInt64(&value) {
print("Decimal: \(value)")
print("Hex: 0x\(String(value, radix: 16))")
}
selectedImgBack = selectedImgBack?.overlayImage(color: UIColor.init(rgb: Int(value)))
selectedImgBack = selectedImgBack?.resized(to: size!)
UIGraphicsBeginImageContext(size!)
selectedImgBack!.draw(in: areaSize)
selectedImgFront!.draw(in: areaSize, blendMode: .normal, alpha: 0.8)
selectedImgFront = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
let selectedImage = selectedImgFront!.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)