如何将图像中的特定颜色更改为不同的颜色

时间:2016-02-09 12:45:42

标签: swift uiimage uikit

我有一个UIView,它的图层内容是图像。

let image = UIImage(names: "myImage")
layer.contents = image.CGImage

此图片有几种颜色。

有没有办法将特定颜色更改为我选择的任何其他颜色?

我找到了更改图像中所有颜色的答案,但没有找到具体的颜色。

answer

2 个答案:

答案 0 :(得分:1)

您无法使用透明背景更改PNG中的特定颜色,但是......我找到了解决方案。

extension UIImage {
    func maskWithColors(color: UIColor) -> UIImage? {
        let maskingColors: [CGFloat] = [100, 255, 100, 255, 100, 255] // We should replace white color.
        let maskImage = cgImage! //
        let bounds = CGRect(x: 0, y: 0, width: size.width * 3, height: size.height * 3) // * 3, for best resolution.
        let sz = CGSize(width: size.width * 3, height: size.height * 3) // Size.
        var returnImage: UIImage? // Image, to return

        /* Firstly we will remove transparent background, because
         maskingColorComponents don't work with transparent images. */

        UIGraphicsBeginImageContextWithOptions(sz, true, 0.0)
        let context = UIGraphicsGetCurrentContext()!
        context.saveGState()
        context.scaleBy(x: 1.0, y: -1.0) // iOS flips images upside down, this fix it.
        context.translateBy(x: 0, y: -sz.height) // and this :)
        context.draw(maskImage, in: bounds)
        context.restoreGState()
        let noAlphaImage = UIGraphicsGetImageFromCurrentImageContext() // new image, without transparent elements.
        UIGraphicsEndImageContext()

        let noAlphaCGRef = noAlphaImage?.cgImage // get CGImage.

        if let imgRefCopy = noAlphaCGRef?.copy(maskingColorComponents: maskingColors) { // Magic.
            UIGraphicsBeginImageContextWithOptions(sz, false, 0.0)
            let context = UIGraphicsGetCurrentContext()!
            context.scaleBy(x: 1.0, y: -1.0)
            context.translateBy(x: 0, y: -sz.height)
            context.clip(to: bounds, mask: maskImage) // Remove background from image with mask.
            context.setFillColor(color.cgColor) // set new color. We remove white color, and set red.
            context.fill(bounds)
            context.draw(imgRefCopy, in: bounds) // draw new image
            let finalImage = UIGraphicsGetImageFromCurrentImageContext()
            returnImage = finalImage! // YEAH!
            UIGraphicsEndImageContext()
        }
        return returnImage
    }
}

对于调用此函数,请使用这样的代码......

let image = UIImage(named: "Brush").maskWithColor(color: UIColor.red)

结果:

Before, and after using function.

答案 1 :(得分:-3)

您无法更改图像颜色......唯一的方法是更改​​任何事件或其他内容的图像...... 另一种变体是创建一个透明色的图像,并设置视图的背景颜色或放置图像的位置......