2
我正在製作一個應用程序,用於更改地圖上的顏色以突出顯示一個國家/地區。它就像一個代碼系統,其中一個國家將具有特定的顏色,如果條件允許,該顏色將變爲黃色,其餘的將變爲綠色。它與基於用戶輸入的標記系統類似,以突出特定的國家。我以前看過這篇文章,我修改了它,因此它可以使用參數作爲檢測顏色。 https://codedump.io/share/gEsdbwFbGT3T/1/change-color-of-certain-pixels-in-a-uiimage將基於RBG值的UIImage中的特定像素更改爲不同的RBG顏色
這裏是修改後的代碼:
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值檢測黑色以外的顏色並將其更改爲另一個?