我想将任何 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
}
关于ios - 如何更改 UIImage 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49242964/