ios - 如何更改 UIImage 颜色?

标签 ios swift image image-processing uiimage

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

img

enter image description here

...所以我当然可以遍历 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/

相关文章:

ios - 无效更新 : invalid number of rows in section 0. 更新后现有部分中包含的行数 (3)

ios - 如何计算 iOS 上 CouchbaseLite 的复制进度?

php - 无法从 JSON 响应中获取正确的字符串?

ios - 如何将已排序的 NSStrings 的 NSArray 拆分为 NSMutableArrays 的 NSMutableArray

ios - 使用自定义加密系统覆盖 ATS 中使用的默认加密系统

swift - 如何在 Swift 中为日期选择器设置特定的默认时间

swift - Swift 中从 TableView 到导航 Controller 的 Segue

ios - 自动增强 UIImageView 且不旋转

javascript - 如果 div 没有 img 标签,请向 div 添加 "no image"img (Javascript 或 Jquery)

html - Shopify 图像 slider - 始终扩展到用户全屏