在swift中将基于rbg值的UIImage中的特定像素更改为不同的RBG颜色


我正在制作一个应用程序,改变地图上的颜色来突出显示一个国家。这就像一个代码系统,其中一个国家将具有特定的颜色,如果条件允许,该颜色将更改为黄色,其余的将变为绿色。它类似于标签系统,根据用户的输入突出显示特定的国家。我之前看过一篇关于这个的文章,我对它进行了修改,这样它就可以使用参数作为检测颜色。https://codedump.io/share/gEsdbwFbGT3T/1/change-color-of-certain-pixels-in-a-uiimage

修改后的代码如下:

func processPixelsInImage(inputImage: UIImage, r: UInt8, b: UInt8, g: UInt8) -> UIImage {
        let inputCGImage     = inputImage.CGImage
        let colorSpace       = CGColorSpaceCreateDeviceRGB()
        let width            = CGImageGetWidth(inputCGImage)
        let height           = CGImageGetHeight(inputCGImage)
        let bytesPerPixel    = 4
        let bitsPerComponent = 8
        let bytesPerRow      = bytesPerPixel * width
        let bitmapInfo       = CGImageAlphaInfo.PremultipliedFirst.rawValue | CGBitmapInfo.ByteOrder32Little.rawValue

        let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)!
        CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), inputCGImage)

        let pixelBuffer = UnsafeMutablePointer<UInt32>(CGBitmapContextGetData(context))

        var currentPixel = pixelBuffer

        for _ in 0 ..< Int(height) {
            for _ in 0 ..< Int(width) {
                let pixel = currentPixel.memory

                if red(pixel) == r && green(pixel) == g && blue(pixel) == b {
                    currentPixel.memory = rgba(red: 0, green: 170, blue: 0, alpha: 255)
                }
                currentPixel = currentPixel.successor()
            }
        }

        let outputCGImage = CGBitmapContextCreateImage(context)
        let outputImage = UIImage(CGImage: outputCGImage!, scale: inputImage.scale, orientation: inputImage.imageOrientation)

        return outputImage
    }

    func alpha(color: UInt32) -> UInt8 {
        return UInt8((color >> 24) & 255)
    }

    func red(color: UInt32) -> UInt8 {
        return UInt8((color >> 16) & 255)
    }

    func green(color: UInt32) -> UInt8 {
        return UInt8((color >> 8) & 255)
    }

    func blue(color: UInt32) -> UInt8 {
        return UInt8((color >> 0) & 255)
    }

    func rgba(red red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) -> UInt32 {
        return (UInt32(alpha) << 24) | (UInt32(red) << 16) | (UInt32(green) << 8) | (UInt32(blue) << 0)
    }

当我使用黑色(0,0,0)以外的RGB值时,它不会检测和更改颜色。由于不同的数据类型,我不确定rgb值与普通CG颜色相比是否有不同的缩放比例,但我仍然不确定如何充分使用此功能。如何使用RGB值检测黑色以外的颜色并将其更改为其他颜色?

转载请注明出处:http://www.fortunesungroup.com/article/20230331/1388155.html