How can I change this black shade (gradient) to some colored shade?

Viewed 68

I want to use the actual color of the image, apply alpha effect pixel by pixel and create something like this but in colored way. How can I do it?

I tried giving it a color but it turned my image from white to pink.

In this code, I go pixel by pixel and change the pixel alpha to 0 or 1. If I make the rgb to black e.g 0, it creates the right gradient, however when I use rgb values other than 0, it turns into white shades which is not required

func processPixels(in image: UIImage) -> UIImage? {
    let cgImage = convertCIImageToCGImage(inputImage: image)
    guard let inputCGImage = cgImage else {
        print("unable to get cgImage")
        return nil
    }
    let colorSpace       = CGColorSpaceCreateDeviceRGB()
    let width            = inputCGImage.width
    let height           = inputCGImage.height
    let bytesPerPixel    = 4
    let bitsPerComponent = 8
    let bytesPerRow      = bytesPerPixel * width
    let bitmapInfo       = RGBA32.bitmapInfo

    guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
        print("unable to create context")
        return nil
    }
    context.draw(inputCGImage, in: CGRect(x: 0, y: 0, width: width, height: height))

    guard let buffer = context.data else {
        print("unable to get context data")
        return nil
    }

    let pixelBuffer = buffer.bindMemory(to: RGBA32.self, capacity: width * height)

    var rowAlpha: UInt8 = 0
    for row in 0 ..< Int(height) {
        rowAlpha = UInt8(row)
        for column in 0 ..< Int(width) {
            let offset = row * width + column
            if pixelBuffer[offset].alphaComponent > 0 {
                pixelBuffer[offset] = RGBA32(red: pixelBuffer[offset].redComponent, green:  pixelBuffer[offset].greenComponent, blue: pixelBuffer[offset].blueComponent, alpha: rowAlpha)
            }
        }
    }

    let outputCGImage = context.makeImage()!
    let outputImage = UIImage(cgImage: outputCGImage, scale: image.scale, orientation: image.imageOrientation)

    return outputImage
}

func convertCIImageToCGImage(inputImage: UIImage) -> CGImage? {
    guard let ciImage = inputImage.ciImage else {
        print("unable to get ciImage")
        return nil
    }
    let context = CIContext(options: nil)
    if let cgImage = context.createCGImage(ciImage, from: ciImage.extent) {
        return cgImage
    }
    return nil
}

Original Image

Original Image

Gradient Image without color image with black color

0 Answers
Related