如何在iOS上创建单色UIImage

时间:2017-11-03 09:10:12

标签: ios swift uiimage cifilter

我有一个UIImage来自服务器,我需要在UI中呈现为单色图像,其中给定的单一颜色也可以是任意的。实现它的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

在我目前的方法中,我使用以下方法返回给定图像和颜色的单色图像:

fileprivate func monochromaticImage(from image: UIImage, in color: UIColor) -> UIImage {
    guard let img = CIImage(image: image) else {
        return image
    }
    let color = CIColor(color: color)
    guard let outputImage = CIFilter(name: "CIColorMonochrome",
                               withInputParameters: ["inputImage" : img,
                                                     "inputColor" : color])?.outputImage  else {
        return image
    }
    let context = CIContext()
    if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
        let newImage = UIImage(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation)
        return newImage
    }
    return image
}
相关问题