如何在Swift中计算色彩合成?

时间:2018-12-05 07:46:54

标签: swift image-processing colors core-graphics

我正在尝试为我的照片编辑器应用创建橡皮擦工具,例如在 Photoshop 中(或可以从图像中删除定义的颜色),例如,用户将在图像上绘制具有所需颜色的线条,触摸立即结束后,我的功能将处理图像。

我创建了一个方法,它可以与某些颜色配合使用,例如白色,黑色,黄色等,但是当我选择0.5 alpha的颜色时,它就无法正常工作! 我认为我的综合计算错了,所以有人可以帮助我吗?

这是我的计算方法:

extension UIImage {

func getImageRemovedDefinedColor(choosedColor: UIColor) -> UIImage? {

    let image = UIImage(data: self.jpegData(compressionQuality: 1.0)!)!
    let rawImageRef: CGImage = image.cgImage!

    let components = choosedColor.cgColor.components!

    var colorMasking: [CGFloat] = []
    var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0

    if choosedColor.isEqual(UIColor.white) {

        colorMasking = [222, 255, 222, 255, 222, 255]

    } else if choosedColor.isEqual(UIColor.black) {

        colorMasking = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

    } else {

        if components.count > 3 {

            red = components[0]
            green = components[1]
            blue = components[2]
            alpha = components[3]

            red = red * 255.0
            green = green * 255.0
            blue = blue * 255.0
            alpha = alpha * 255.0

            let redRange: [CGFloat] = {
                return [max(red - (alpha / 2.0), 0.0), min(red + (alpha / 2.0), 255.0)]
            }()

            let greenRange: [CGFloat] = {
                return [max(green - (alpha / 2.0), 0.0), min(green + (alpha / 2.0), 255.0)]
            }()

            let blueRange: [CGFloat] = {
                return [max(blue - (alpha / 2.0), 0.0), min(blue + (alpha / 2.0), 255.0)]
            }()

            colorMasking = [redRange[0], redRange[1], greenRange[0], greenRange[1], blueRange[0], blueRange[1]]
        }
    }

    print(colorMasking)

    UIGraphicsBeginImageContext(image.size);

    let maskedImageRef = rawImageRef.copy(maskingColorComponents: colorMasking)
    UIGraphicsGetCurrentContext()?.translateBy(x: 0.0,y: image.size.height)
    UIGraphicsGetCurrentContext()?.scaleBy(x: 1.0, y: -1.0)
    UIGraphicsGetCurrentContext()?.draw(maskedImageRef!, in: CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height))
    let result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result

}

注意:也许我在使用此工具时完全错了,如果您对“如何使用Swift创建橡皮擦工具”有其他想法,请与我们分享。

所有想法都可以接受,谢谢。

0 个答案:

没有答案