【问题标题】:how to change specific color in image to a different color如何将图像中的特定颜色更改为不同的颜色
【发布时间】:2016-02-09 12:45:41
【问题描述】:

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

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

这张图片有几种颜色。

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

我找到了更改图像中所有颜色但不是特定颜色的答案。

answer

【问题讨论】:

标签: swift uiimage uikit


【解决方案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)

结果:

【解决方案2】:

您无法更改图像颜色...唯一的方法是在任何事件或某事上更改图像... 另一种变体是创建一个具有透明颜色的图像,并设置视图的背景颜色或放置图像的位置...

【讨论】:

  • 我认为它的东西:D
  • 用户只有 2 天。他需要时间来了解SF规则。 stackoverflow.com/help/how-to-answer
  • 好吧,如果有不对的地方很抱歉,不过我觉得除了图片的透明色之外没有别的可能……是的,smth是什么……
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 2020-10-24
  • 2021-08-08
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多