如何更改 UIImage 颜色?

How to change UIImage color?

我想将任何 UIImage 的每个像素的颜色更改为特定颜色(所有像素都应获得相同的颜色):

... 所以我当然可以 遍历 UIImage 的每个像素 并将其设置为 红色、绿色和蓝色 属性 到 0 以获得黑色外观。

但显然这不是为图像重新着色的有效方法,我很确定有几种更有效的方法可以实现这一点,而不是循环遍历图像的每个像素。


func recolorImage(image: UIImage, color: String) -> UIImage {
    let img: CGImage = image.cgImage!
    let context = CGContext(data: nil, width: img.width, height: img.height, bitsPerComponent: 8, bytesPerRow: 4 * img.width, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
    context.draw(img, in: CGRect(x: 0, y: 0, width: img.width, height: img.height))
    let data = context.data!.assumingMemoryBound(to: UInt8.self)
    for i in 0..<img.height {
        for j in 0..<img.width {
           // set data[pixel] ==> [0,0,0,255]
        }
    }
   let output = context.makeImage()!
   return UIImage(cgImage: output)
 }

非常感谢 Ayn 的帮助!

由于原始图像的每个像素都是相同的颜色,因此结果图像不依赖于原始图像的像素。您的方法实际上只需要图像的大小,然后创建一个具有该大小的新图像,并填充一种颜色。

func recolorImage(image: UIImage, color: UIColor) -> UIImage {
    let size = image.size
    UIGraphicsBeginImageContext(size)
    color.setFill()
    UIRectFill(CGRect(origin: .zero, size: size))
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}