在iOS中滤镜的API是指Core Image框架定义好的,并且非常重要。
使用滤镜
iOS有90多种滤镜,Mac有120多种,而且有很多的参数和属性。
滤镜使用流程可以分成三步:
- 创建滤镜CIFilter对象;
- 设置滤镜参数;
- 输出结果;
实例:旧色调和高斯模糊滤镜
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iamgeView;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (nonatomic, strong) UIImage *image;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedControl;
- (IBAction)changeValue:(id)sender;
- (IBAction)segmentSelected:(id)sender;
/**
操作旧色调
*/
-(void)filterSepiaTone;
/**
操作高斯模糊
*/
-(void)filterGaussianBlur;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:@"flower" ofType:@"jpg"];
_image = [[UIImage alloc] initWithContentsOfFile:path];
if (_segmentedControl.selectedSegmentIndex == 0)
{
[self filterSepiaTone];
}
else
{
[self filterGaussianBlur];
}
}
-(void)filterSepiaTone
{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *cImage = [CIImage imageWithCGImage:_image.CGImage];
CIImage *result;
CIFilter *sepiaTone = [CIFilter filterWithName:@"CISepiaTone"];
[sepiaTone setValue:cImage forKey:@"inputImage"];
double value = [_slider value];
[sepiaTone setValue:[NSNumber numberWithDouble:value] forKey:@"inputIntensity"];
result = [sepiaTone valueForKey:@"outputImage"];
CGImageRef imageRef = [context createCGImage:result fromRect:CGRectMake(0, 0, _iamgeView.frame.size.width, _iamgeView.frame.size.height)];
UIImage *image = [UIImage imageWithCGImage:imageRef];
_iamgeView.image = image;
NSString *text = [[NSString alloc] initWithFormat:@"旧色调:%.2f", value];
_label.text = text;
CFRelease(imageRef);
}
-(void)filterGaussianBlur
{
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *cImage = [CIImage imageWithCGImage:_image.CGImage];
CIImage *result;
CIFilter *gaussianBlur = [CIFilter filterWithName:@"CIGaussianBlur"];
[gaussianBlur setValue:cImage forKey:@"inputImage"];
double value = [_slider value];
value *= 10;
[gaussianBlur setValue:[NSNumber numberWithDouble:value] forKey:@"inputRadius"];
result = [gaussianBlur valueForKey:@"outputImage"];
CGImageRef imageRef = [context createCGImage:result fromRect:CGRectMake(0, 0, _iamgeView.frame.size.width, _iamgeView.frame.size.height)];
UIImage *image = [UIImage imageWithCGImage:imageRef];
_iamgeView.image = image;
NSString *text = [[NSString alloc] initWithFormat:@"高斯模糊:%.2f", value];
_label.text = text;
CFRelease(imageRef);
}
- (IBAction)segmentSelected:(UIButton *)sender
{
if (_segmentedControl.selectedSegmentIndex == 0)
{
[self filterSepiaTone];
}
else
{
[self filterGaussianBlur];
}
}
- (IBAction)changeValue:(id)sender
{
if (_segmentedControl.selectedSegmentIndex == 0)
{
[self filterSepiaTone];
}
else
{
[self filterGaussianBlur];
}
}
@end