It is necessary to change the color of the image to 00ff00.
But it turns out to 4fff00.
I tried it in two ways. The result is the same.
internal static func imageColorMatrix1(image: UIImage) -> UIImage? {
let colorMatrix = CIFilter(name: "CIColorMatrix")
colorMatrix?.setDefaults()
colorMatrix?.setValue(CIImage(cgImage: image.cgImage!), forKey: kCIInputImageKey)
colorMatrix?.setValue(CIVector(x: 0.0, y: 0.0, z: 0.0, w: 0.0), forKey: "RVector")
colorMatrix?.setValue(CIVector(x: 0.0, y: 0.0, z: 0.0, w: 0.0), forKey: "GVector")
colorMatrix?.setValue(CIVector(x: 0.0, y: 0.0, z: 0.0, w: 0.0), forKey: "BVector")
colorMatrix?.setValue(CIVector(x: 0.0, y: 0.0, z: 0.0, w: 1.0), forKey: "AVector")
colorMatrix?.setValue(CIVector(x: 0.0, y: 1.0, z: 0.0, w: 0.0), forKey: "biasVector")
let outIm = colorMatrix?.outputImage
let cgIm = CIContext().createCGImage(outIm!, from: outIm!.extent)
return UIImage(cgImage: cgIm!)
}
or
class ColorFilter: CIFilter {
var inputImage: CIImage?
var inputColor: UIColor?
let kernel: CIColorKernel = {
let kernelString = "kernel vec4 colorize(__sample pixel, vec4 color)n"
+ "{n"
//+ "pixel.rgb = color.rgb;n"
+ "pixel.r = 0.0;n"
+ "pixel.g = 1.0;n"
+ "pixel.b = 0.0;n"
+ "return pixel;n"
+ "}n"
return CIColorKernel(source: kernelString)!
}()
override var outputImage: CIImage? {
guard let inputImage = inputImage else {
return nil
}
guard let inputColor = inputColor else {
return nil
}
let inputs = [inputImage, CIColor(color: inputColor)] as [Any]
return kernel.apply(extent: inputImage.extent, arguments: inputs)
}
}
Calling the class as follows:
internal static func imageColorMatrix1(image: UIImage) -> UIImage? {
let colorFilter = ColorFilter()
colorFilter.inputColor = UIColor.green
colorFilter.inputImage = CIImage(cgImage: image.cgImage!)
let outIm = colorFilter.outputImage
let context = CIContext()
let cgIm = context.createCGImage(outIm!, from: outIm!.extent)
return UIImage(cgImage: cgIm!)
}
I display it on the UIImageView.
Where am I wrong?
2
Answers
I tried it. The result is as follows: 33AE00.
I tried my algorithms with other colors as well. There are color distortions everywhere. I will give examples below:
Where can these distortions be introduced? Do I need to use any settings when opening an image?
for passing the hex color create one extension
Use it Like :
Change BaseViewController with your controller’s name