您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 濾鏡實戰:CIImage、CIFilter 與濾鏡鏈的組合玩法

編輯:iOS 程式設計技術

「濾鏡」這個詞,有些同學可能覺得陌生。但你一定用過它——那些一鍵美白磨皮的美顏相機、隨手一調就很有質感的修圖 App,背後都是濾鏡在工作。所以下次看到網上的精修照片,記得保持一分清醒。

廢話不多說,進入正題。

一、CoreImage 框架介紹

  1. CoreImage 是蘋果提供的一套圖像處理框架,構建在 OpenGL 之上。
  2. 它充分利用 GPU 進行硬件加速,處理圖像的效率遠高於 CPU 逐像素計算。
  3. 框架內置了上百種現成濾鏡,涵蓋色彩調整、模糊、扭曲、邊緣檢測等各種類型。
  4. 它能一次性對一張圖片或視頻的某一幀施加多種視覺效果——這就是濾鏡鏈。
  5. 濾鏡之間可以串聯起來,把多個效果依次疊加,最終合成輸出。

二、三個核心類

CIImage:保存圖像數據的類,可以與 UIImage 互相轉換。

CIFilter:濾鏡類。對濾鏡對象進行設置時,採用的是鍵值編碼(KVC)方式。

CIContext:上下文,是真正執行圖像處理的對象。特別注意:濾鏡輸出的並不是合成的最終結果,必須借助 CIContext 才能把圖像渲染出來。

三、使用步驟

  1. 準備一個 CIImage 對象。不能把 UIImage 直接轉成 CIImage,需要先轉成 CGImageRef 再轉。
  2. 創建濾鏡對象,用 KVC 設置各項參數。
  3. 創建 CIContext 上下文。
  4. 合併濾鏡輸出的圖像,得到最終結果。
  5. 把結果賦值給 UIImageView 顯示。
  6. 若想繼續疊加效果,重複上述循環即可。

四、如何查找濾鏡屬性

這裡不需要背,隨時查就好,不然簡直像背英漢大字典。

1. 查詢某個分類下有哪些濾鏡

filterNamesInCategory:

2. 查詢某個濾鏡支持哪些可設置屬性

[CIFilter filterWithName:XXX].attributes

五、準備工作

先把界面搭起來:兩個 Button(一個選照片、一個加效果)、一個 UIImageView。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = YES;

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 200, 500, 600)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:imageView];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 50, 50);
    button.backgroundColor = [UIColor grayColor];
    [button addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(100, 100, 100, 100);
    [button1 setTitle:@"TICK" forState:UIControlStateNormal];
    button1.backgroundColor = [UIColor brownColor];
    [button1 addTarget:self action:@selector(addEffect) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
}

- (void)tap:(UIButton *)sender{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    // picker.sourceType 默認是相冊
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    // 得到的照片顯示在視圖上
    imageView.image = image;
}

濾鏡的整體流程一張圖就能說清:

六、濾鏡核心代碼

- (void)addFilter{
    // 1. 需要有一個輸入的原圖
    CIImage *inputImage = [CIImage imageWithCGImage:imageView.image.CGImage];

    // 2. 創建一個濾鏡
    CIFilter *filter = [CIFilter filterWithName:@"CIBumpDistortion"];

    // 這裡使用KVC的方式給filter設置屬性
    [filter setValue:inputImage forKey:kCIInputImageKey];
    // 設置凹凸效果的半徑,越大越明顯
    [filter setValue:@500 forKey:kCIInputRadiusKey];
    // CIVector 表示 X Y 坐標的一個類
    // 設置中心點
    [filter setValue:[CIVector vectorWithX:200 Y:200] forKey:kCIInputCenterKey];

    // 3. 用CIContext把原圖和濾鏡效果合成
    CIImage *outputImage = filter.outputImage;
    // 創建一個圖像處理的上下文
    CIContext *context = [CIContext contextWithOptions:nil];

    // 把原圖和濾鏡合併起來,得到包含濾鏡效果的圖像
    /**
     * image    : 合成之後的圖像
     * fromRect : 合成之後圖像的尺寸,即 image.extent
     */
    CGImageRef imageRef = [context createCGImage:outputImage fromRect:outputImage.extent];
    imageView.image = [UIImage imageWithCGImage:imageRef];
}

七、兩個容易踩的坑

坑一:類型轉換

濾鏡需要的輸入是 CIImage,不是 CGImage。很多人直接寫 [CIImage imageWithCGImage:] 傳入錯誤類型,導致濾鏡不生效。務必確認轉換鏈是 UIImage → CGImage → CIImage。

坑二:屬性查詢路徑

所有可用的濾鏡與可設置屬性都只能靠打印查詢,而且這一步特別容易暈。方法如下:

1. 查詢某分類下包含哪些濾鏡:filterNamesInCategory:

按住 command 點擊 CIFilter 進入頭文件,大約第 128 到 148 行全是效果分類常量。選中其中一個分類,打印:

NSLog(@"%@", [CIFilter filterNamesInCategory:kCICategoryDistortionEffect]);

輸出就是該分類下包含的所有濾鏡名,從中挑一個複製出來。

2. 查詢某濾鏡支持哪些可設置屬性:attributes

NSLog(@"%@", [CIFilter filterWithName:@"剛才複製的濾鏡名"].attributes);

輸出的就是這個濾鏡所有可設置的鍵值對。

整體流程串起來就是:

CIFilter → 點進頭文件找到某個 category → 用 filterNamesInCategory: 打印出該分類下的濾鏡 → 從中複製一個 → 用 filterWithName:].attributes 拿到所有可設置屬性 → 用 setValue:forKey: 逐項設置。

注意最後一步的 key 也需要回 CIFilter 頭文件中查找(大約在 165 到 191 行),找一個和你想要的屬性對應的常量,比如 kCIInputRadiusKey。

八、濾鏡鏈:效果的嵌套組合

所謂濾鏡鏈,就是把多個濾鏡串起來依次作用在同一張圖上。

#pragma mark - 濾鏡鏈
// 再次添加濾鏡,形成濾鏡鏈
- (void)addfilterLinkerWithImage:(CIImage *)image{
    CIFilter *filter = [CIFilter filterWithName:@"CISepiaTone"];
    [filter setValue:image forKey:kCIInputImageKey];
    [filter setValue:@0.5 forKey:kCIInputIntensityKey];

    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef imageRef = [context createCGImage:filter.outputImage
                                       fromRect:filter.outputImage.extent];
    imageView.image = [UIImage imageWithCGImage:imageRef];

    // 保存圖片到相冊
    // 注意不能直接保存 outputImage,因為它還沒合成
    UIImageWriteToSavedPhotosAlbum(imageView.image, self,
        @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

寫法上有個小技巧:與其每加一個濾鏡就合成一次,不如把每個濾鏡的 outputImage 當作下一個濾鏡的 inputImage 一路傳下去,只在最後一步調用一次 createCGImage:fromRect:。這樣只需要一個 CIContext,代碼更乾淨,性能也更好。

另外提醒一下,CIContext 的創建開銷不小,實踐中建議復用同一個實例,不要每次疊加濾鏡都新建。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved