1. 有哪些滤镜效果
使用苹果自带的CoreImage框架对图片进行处理,用CoreImage框架里的CIFilter对图片进行滤镜处理,首先我们应该了解下CoreImage框架能够对图像进行那些处理和拥有哪些特效。
先代码看下苹果给我们提供了将近200中滤镜效果
// 这里我们可以看到总共有多少种滤镜
NSArray *filterNames = [CIFilter filterNamesInCategory:@"CICategoryBuiltIn"]; NSLog(@"总共有%ld种滤镜效果:%@",filterNames.count,filterNames);
//以一个具体分类中的滤镜信息
NSArray* filters = [CIFilter filterNamesInCategory:kCICategoryDistortionEffect];
for (NSString* filterName in filters) {
NSLog(@"filter name:%@",filterName);
// 我们可以通过filterName创建对应的滤镜对象
CIFilter* filter = [CIFilter filterWithName:filterName];
NSDictionary* attributes = [filter attributes];
// 获取属性键/值对(在这个字典中我们可以看到滤镜的属性以及对应的key) NSLog(@"filter attributes:%@",attributes);
}
image
可以看到CoreImage中的CIFilter效果确实很多,分很多种类别,每个分类中又有多个效果
image我们点击第一个CIBoxBlur为例可以看到滤镜参数还有具体的效果,其中需要注意的是不同的滤镜对应的参数设置中的key值是不同的,一定要对应起来不然程序会因为找不到这个key值崩溃
image2.滤镜怎么实现
CoreImage框架提供三个API来实现滤镜效果
CIContext:核心API,来管理所有的图片处理操作。
CIFilter:过滤器,通过在创建CIFilter时需要传入不同的参数即可创建不同类型的过滤器。 CIImage:它代表 Core Image 过滤器处理的图片,CIFilter过滤器的输入图片,输出图片都由该CIImage代表。
CIContext:创建分三种方式,因为采用基于GPU的CIContext将可以获得更好的性能,因此,一般建议创建基于GPU的CIContext,但基于GPU的CIContext对象无法跨应用访问,这个问题需要注意
//1.创建基于CPU的CIContext对象
self.context = [CIContext contextWithOptions:
[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:kCIContextUseSoftwareRenderer]];
//2.创建基于GPU的CIContext对象
self.context = [CIContext contextWithOptions: nil];
//3.创建基于OpenGL优化的CIContext对象,可获得实时性能
self.context = [CIContext contextWithEAGLContext:[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]];
// 将UIImage转换成CIImage
CIImage *ciImage = [[CIImage alloc] initWithImage:[UIImage imageNamed:@"WechatIMG1.jpeg"]];
// 创建滤镜
CIFilter *filter = [CIFilter filterWithName:_dataSourse[indexPath.row]
keysAndValues:kCIInputImageKey, ciImage, nil];
[filter setDefaults];
// 获取绘制上下文
CIContext *context = [CIContext contextWithOptions:nil];
// 渲染并输出CIImage
CIImage *outputImage = [filter outputImage];
// 创建CGImage句柄
CGImageRef cgImage = [self.context createCGImage:outputImage
fromRect:[outputImage extent]];
imageview.image = [UIImage imageWithCGImage:cgImage];
// 释放CGImage句柄
CGImageRelease(cgImage);
看下代码实现的效果:
image