學(xué)習(xí)濾鏡,首先要了解它是干什么的。
濾鏡->就是給圖像 添加效果
1、框架介紹
(1)CoreImage
(2)是一個圖像框架 它基于OpenGL頂層創(chuàng)建底層則用著色器來處理圖像
(3)它利用了GPU基于硬件加速來處理圖像
(4)CoreImage中有很多濾鏡
(5)它們能夠一次給予一張圖像或者視頻幀多種視覺效果 -> 濾鏡鏈
(6)而且濾鏡可以連接起來組成一個濾鏡鏈 把濾鏡效果疊加起來處理圖像
2、類的介紹
(1)CIImage:保存圖像數(shù)據(jù)的類 CGImageRef->圖像中的數(shù)據(jù)
(2)CIFilter:濾鏡類 圖片屬性進(jìn)行細(xì)節(jié)處理的類 它對所有的像素進(jìn)行操作 用鍵-值 (KVC)來設(shè)置
(3)CIContext:上下文是實(shí)現(xiàn)對圖像處理的具體對象 -> 濾鏡對象輸出的圖像并不是合成之后的圖像 需要使用圖像處理的上下文 合并輸出圖像
3、效果介紹 100+效果可以通過attributes查找需要設(shè)置的參數(shù)內(nèi)容
使用步驟
1、查詢效果分類里面的效果 filterNamesInCategory:
1)按住command 點(diǎn)擊CIFilter 進(jìn)入接口文件 找到第128行-148行全部都是 效果分類
(2)選擇其中某一個分類 NSLog [CIFilter filterNamesInCategory:剛才拷貝的分類];->打印出來的 是這個分類包含的所有 效果 -> 拷貝選擇其中的某一個效果
2、查詢效果的屬性
[CIFilter filterWithName:xxx].attributes
NSLog -> [CIFilter filterWithName:剛才拷貝選擇其中的某一個效果].attributes ->得到這個濾鏡所有可以設(shè)置的屬性
3、使用步驟
(1)實(shí)例CIImage -> 先把UIImage ->CGImageRef -> CIImage
(2)創(chuàng)建CIFilter濾鏡并給濾鏡設(shè)置屬性(KVC)
(3)創(chuàng)建CIContext上下文
(4)合并濾鏡輸出的圖像 -> 得到一個合并之后的圖像
(5)賦給UIImageView對象進(jìn)行顯示
(6)如果想使用濾鏡鏈 繼續(xù)循環(huán)上面步驟 可以再次疊加效果
// 通過分類 查找這個分類 里面 所有的濾鏡效果
// 分類的名字 -> CIFilter提供了分類的名字
NSLog(@"%@",[CIFilter filterNamesInCategory:kCICategoryStillImage]);
//查詢 可以設(shè)置 哪些 參數(shù)
![Uploading A4CA1B27-470C-4B9A-A885-A470E4B98251_377722.png . . .]
NSLog(@"%@",[CIFilter filterWithName:@"CIKaleidoscope"].attributes);
// 1、源圖
CIImage *inputImage = [CIImage imageWithCGImage:imageView.image.CGImage];
// 2、濾鏡的對象
CIFilter *filter = [CIFilter filterWithName:@"CIColorMonochrome"];
[filter setValue:inputImage forKey:kCIInputImageKey];//KVC賦值
[filter setValue:[CIColor colorWithRed:1.0 green:0.7262 blue:0.1014 alpha:1] forKey:kCIInputColorKey];
[filter setValue:@0.5 forKey:kCIInputIntensityKey];
// 3、context 文本上下文 合成
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *outputImage = filter.outputImage;
CGImageRef image = [context createCGImage:outputImage fromRect:outputImage.extent];
imageView.image = [UIImage imageWithCGImage:image];
NSLog(@"%@",outputImage);
未改變的圖片:

改變之后的圖片:

下面是一個保存圖片的方法,可以把圖片保存到相冊中。
UIImageWriteToSavedPhotosAlbum(UIImage *image, __nullable id completionTarget, __nullable SEL completionSelector, void * __nullable contextInfo)
最后,還有濾鏡鏈,就是在原來的基礎(chǔ)上再次添加濾鏡。這些,大家可以自己試試。