如何将这种黑色阴影渐变更改为某些彩色阴影?

问题描述

我想使用图像的实际颜色,逐像素应用alpha效果,并以彩色方式创建类似的内容。我该怎么办?

我尝试给它添加颜色,但是它使我的图像从白色变成了粉红色。

在此代码中,我逐像素移动并将像素alpha更改为0或1。如果将rgb设置为黑色(例如0),则会创建正确的渐变,但是当我使用非0的rgb值时,它将变为变成不需要的白色阴影

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,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

原始图片

无颜色的渐变图像

image with black color

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...