Core Image API架構(gòu)
Core Image的插件架構(gòu)允許編寫自定義濾鏡與系統(tǒng)濾鏡集成來擴(kuò)展功能蟆盐。Core Image需要context對(duì)象來實(shí)現(xiàn)移必。
找可用濾鏡
向Core Image的kCICategoryBuiltIn類請(qǐng)求得到濾鏡名室谚。或者使用Quartz Composer里的Filter查看并且進(jìn)行組合查看效果。這個(gè)范例也可以查看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個(gè)內(nèi)置濾鏡猪瞬,iOS上有127個(gè)
創(chuàng)建濾鏡
let blurFilter = CIFilter(named:"CIGaussianBlur”) //根據(jù)濾鏡列表里的濾鏡名,可以創(chuàng)建一個(gè)濾鏡對(duì)象入篮,比如高斯模糊濾鏡
對(duì)濾鏡對(duì)象設(shè)置參數(shù)
blurFilter.setValue(10.0 forKey:"inputRadius”) //設(shè)置模糊濾鏡的模糊半徑
查詢?yōu)V鏡屬性
查看濾鏡的輸入和輸出參數(shù)可以獲取inputKeys和outputKeys數(shù)組陈瘦,通過濾鏡提供的attributes字典。
//CIColorControls濾鏡對(duì)應(yīng)的inputBrightness參數(shù)字典
inputBrightness = {
CIAttributeClass = NSNumber;
CIAttributeDefault = 0;
CIAttributeIdentity = 0;
CIAttributeMin = -1;
CIAttributeSliderMax = 1;
CIAttributeSliderMin = -1;
CIAttributeType = CIAttributeTypeScalar;
};
示例創(chuàng)建一個(gè)19 世紀(jì)錫版照風(fēng)格圖像的濾鏡
使用CIColorMonochrome和CIVignette濾鏡鏈起來可以達(dá)到這種效果潮售。蘋果提供了一個(gè)叫做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
創(chuàng)建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)