gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:44:10 26 4
gpt4 key购买 nike

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

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

这张图片有几种颜色。

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

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

answer

最佳答案

您无法更改具有透明背景的 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.

关于swift - 如何将图像中的特定颜色更改为不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com