繁体   English   中英

如何更改UIImage颜色?

[英]How to change UIImage color?

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

IMG

在此处输入图片说明

...因此,我当然可以循环遍历 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)
 }

艾恩的帮助将不胜感激!

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

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM