Core Image - ZhiJianShuSheng/Read-And-Learn GitHub Wiki

Core Image API架构

Core Image的插件架构允许编写自定义滤镜与系统滤镜集成来扩展功能。Core Image需要context对象来实现。

找可用滤镜

向Core Image的kCICategoryBuiltIn类请求得到滤镜名。或者使用Quartz Composer里的Filter查看并且进行组合查看效果。这个范例也可以查看https://github.com/objcio/issue-21-core-image-explorer。官方提供的Core Image滤镜的完整列表https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP40004346

let filterNames = CIFilter.filterNamesInCategory(kCICategoryBuiltIn) as [String] //目前OS X有169个内置滤镜,iOS上有127个

创建滤镜

let blurFilter = CIFilter(named:"CIGaussianBlur”) //根据滤镜列表里的滤镜名,可以创建一个滤镜对象,比如高斯模糊滤镜

对滤镜对象设置参数

blurFilter.setValue(10.0 forKey:"inputRadius”) //设置模糊滤镜的模糊半径

查询滤镜属性

查看滤镜的输入和输出参数可以获取inputKeys和outputKeys数组,通过滤镜提供的attributes字典。

//CIColorControls滤镜对应的inputBrightness参数字典
inputBrightness = {
     CIAttributeClass = NSNumber;
     CIAttributeDefault = 0;
     CIAttributeIdentity = 0;
     CIAttributeMin = -1;
     CIAttributeSliderMax = 1;
     CIAttributeSliderMin = -1;
     CIAttributeType = CIAttributeTypeScalar;
};

示例创建一个19 世纪锡版照风格图像的滤镜

使用CIColorMonochrome和CIVignette滤镜链起来可以达到这种效果。苹果提供了一个叫做Quartz Composer的工具用来做Core Image滤镜图表的原型。官方下载地址https://developer.apple.com/downloads/index.action?name=Graphics,试着组合成满意的效果后就可以将其code出来。

let sepiaColor = CIColor(red: 0.76, green: 0.65, blue: 0.54)
let monochromeFilter = CIFilter(name: "CIColorMonochrome",
     withInputParameters: ["inputColor" : sepiaColor, "inputIntensity" : 1.0])
monochromeFilter.setValue(inputImage, forKey: "inputImage")

let vignetteFilter = CIFilter(name: "CIVignette",
     withInputParameters: ["inputRadius" : 1.75, "inputIntensity" : 1.0])
vignetteFilter.setValue(monochromeFilter.outputImage, forKey: "inputImage")

let outputImage = vignetteFilter.outputImage

创建Input Image

滤镜要求类型是CIImage

let inputImage = CIImage(image: uiImage)

//有了CIImage就可以把它用作滤镜的inputImage了
filter.setValue(inputImage, forKey:"inputImage")

滤镜处理生成Output Image

let ciContext = CIContext(options: nil)
let cgImage = ciContext.createCGImage(filter.outputImage, fromRect: inputImage.extent())
let uiImage = UIImage(CGImage: cgImage)

使用OpenGL解决性能问题

let eaglContext = EAGLContext(API: .OpenGLES2)
let ciContext = CIContext(EAGLContext: context)
ciContext.drawImage(filter.outputImage, inRect: outputBounds, fromRect: inputBounds)