首页 > 代码库 > iOS CoreImage图片处理动态渲染(滤镜)

iOS CoreImage图片处理动态渲染(滤镜)

//

//  ViewController.m

//  CoreImageOfDong

//

//  Created by Dong on 15/6/30.

//  Copyright (c) 2015 xindong. All rights reserved.

//

#import "ViewController.h"

#import <GLKit/GLKit.h> // 须要导入此库

@interface ViewController ()

@property (nonatomic, strong) GLKView *glkView; //渲染用的buffer视图(类似流媒体,实时改变)

@property (nonatomic, strong) CIFilter *filter;

@property (nonatomic, strong) CIImage *ciImage;

@property (nonatomic, strong) CIContext *ciContext;

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

        

    UIImage *showImage = [UIImage imageNamed:@"demo1.jpg"];

    CGRect rect = CGRectMake(0, 0, showImage.size.width, showImage.size.height);

    

    // 获取OpenGLES渲染的上下文

    EAGLContext *eagContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    

    // 创建出渲染的buffer

    self.glkView = [[GLKView alloc] initWithFrame:rect context:eagContext];

    [self.glkView bindDrawable]; // 绑定绘制,否则刚開始会黑屏

    [self.view addSubview:self.glkView];

    

    // 创建出CoreImage用的上下文

    self.ciContext = [CIContext contextWithEAGLContext:eagContext options:@{kCIContextWorkingColorSpace : [NSNull null]}];

    

    // CoreImage相关设置

    self.ciImage = [[CIImage alloc] initWithImage:showImage];

    self.filter = [CIFilter filterWithName:@"CISepiaTone"];

    [self.filter setValue:self.ciImage forKey:kCIInputImageKey];

    [self.filter setValue:@(0) forKey:kCIInputIntensityKey];

    

    // 開始渲染

    [self.ciContext drawImage:[self.filter valueForKey:kCIOutputImageKey] inRect:CGRectMake(0, 0, self.glkView.drawableWidth, self.glkView.drawableHeight) fromRect:[self.ciImage extent]];

    [self.glkView display];

    

    // 动态渲染

    UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(30, 500, 200, 10)];

    slider.minimumValue = http://www.mamicode.com/0.f;

    slider.maximumValue = http://www.mamicode.com/10.f;

    [slider addTarget:self action:@selector(changeColorValue:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:slider];

}

- (void)changeColorValue:(UISlider *)slider

{

    [self.filter setValue:self.ciImage forKey:kCIInputImageKey];

    [self.filter setValue:@(slider.value) forKey:kCIInputIntensityKey];

    // 開始渲染

    [self.ciContext drawImage:[self.filter valueForKey:kCIOutputImageKey] inRect:CGRectMake(0, 0, self.glkView.drawableWidth, self.glkView.drawableHeight) fromRect:[self.ciImage extent]];

    [self.glkView display];

}

iOS CoreImage图片处理动态渲染(滤镜)