Change tintcolor image view using kingfihser in swift

427 Views Asked by At

I have a horizontal collection view so when selecting the specific cell will change the color of the image view, the problem is when selecting an image tint color changes successfully on images, and some image's tint color does not work with the right behavior display as the background color on the image.

this is the function to change tint color of image

 func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext()! as CGContext
        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0);
        context.setBlendMode(CGBlendMode.normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        context.clip(to: rect, mask: self.cgImage!)
        context.fill(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }

display image using kingfihser ` imageProduct.kf.setImage(with: URL(string:"imageurl"), placeholder: nil) { result in

                self.imageProduct.image = self.categoryImg.image?.imageWithColor(color1: UIColor.green)

           }`

The tint color must be changed successfully on any image read from url (this is screenshot from issue image when add tint color https://freeimage.host/i/H4nx1s9).

1

There are 1 best solutions below

0
Sudeep P H On

The issue might be related to the alpha channel of the image or the blend mode used in the context. To ensure consistent behaviour across all images, you can modify your imageWithColor like this

func imageWithColor(color: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
    
    let context = UIGraphicsGetCurrentContext()!
    let rect = CGRect(origin: .zero, size: self.size)
    
    // Draw the image
    self.draw(in: rect)
    
    // Apply tint color
    context.setFillColor(color.cgColor)
    context.setBlendMode(.sourceAtop)
    context.fill(rect)
    
    // Create a new image with the tint color
    let tintedImage = UIGraphicsGetImageFromCurrentImageContext()!
    
    UIGraphicsEndImageContext()
    
    return tintedImage
}

You can then use this updated function to set the tint color of the image in your Kingfisher completion block,

imageProduct.kf.setImage(with: URL(string: "imageurl"), placeholder: nil) { result in
    if case .success(let value) = result {
        self.imageProduct.image = value.image.imageWithColor(color: UIColor.green)
    }
}