如何组合过滤器

时间:2017-05-10 16:12:03

标签: ios swift xcode core-graphics cifilter

如何组合图像滤镜?例如,我想使用CIColorControls,CINoiseReduction等。是否有必要创建几个过滤器并初始化它们?或者还有另一种方式吗?

var colorControls: CIFilter
var noiseReduction: CIFilter
...

func init() {
   colorControls = CIFilter.init(name: "CIColorControls")!
   noiseReduction = CIFilter.init(name: "CINoiseReduction")!
   ...
}

1 个答案:

答案 0 :(得分:4)

您可以逐个应用过滤器:

func filter(image: CIImage) -> CIImage? {
    guard let colorControls = CIFilter(name: "CIColorControls"),
          let noiseReduction = CIFilter(name: "CINoiseReduction") else { return nil }
    colorControls.setValue(image, forKey: kCIInputImageKey)
    ... // add some CIColorControls filter manipulations
    guard let imageWithFirstFilter = colorControls.value(forKey: kCIOutputImageKey) as? CIImage else { return nil }
    noiseReduction.setValue(imageWithFirstFilter, forKey: kCIInputImageKey)
    ... // add some CINoiseReduction filter manipulations
    guard let imageWithBothFilters = noiseReduction.value(forKey: kCIOutputImageKey) as? CIImage else { return nil }
    return imageWithBothFilters
}

有点不同的方式:

func apply(_ filter: CIFilter?, for image: CIImage) -> CIImage {
    guard let filter = filter else { return image }
    filter.setValue(image, forKey: kCIInputImageKey)
    guard let filteredImage = filter.value(forKey: kCIOutputImageKey) else { return image }
    return filteredImage
}

使用:

image = apply(colorControls, for: image)