给图片增加高斯模糊效果

前一阵研究了图片的滤镜效果,今天单独把高斯模糊的拿出来,供小伙伴们一起学习。

高斯模糊的效果其实灰常简单,苹果这边已经给了一些现成的封装CIFilter,下面一起来看一看代码吧~


//
//  ViewController.m
//  GS
//
//  Created by a111 on 16/3/7.
//  Copyright © 2016年 司小文. All rights reserved.
//

#import "ViewController.h"
#define nav 64 //导航条高度
#define imgViewH 200 //图片高度

@interface ViewController (){
    CIFilter *filter;//全局filter
    UIImageView *_imgView_Top;//上方图片
    UIImage *_img_original;//原始图片
    float radius;//高斯模糊度
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"高斯模糊demo";
    
    //高斯模糊度 (这个数值由你自己设定,越大模糊度越高)
    radius = 10.;
    
    //原始图片img
    _img_original = [UIImage imageNamed:@"20140622212336_N284Y.jpg"];
    
    //图片
    _imgView_Top = [[UIImageView alloc] initWithFrame:CGRectMake(0, nav, self.view.frame.size.width,imgViewH)];
    _imgView_Top.image = _img_original;
    [self.view addSubview:_imgView_Top];
    
    //高斯模糊
    filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:@(radius) forKey:@"inputRadius"];
    
    //将图片转换成文件
    NSData *imageData = UIImagePNGRepresentation(_img_original);
    
    //将文件转换成CIImage
    CIImage *beginImage =[CIImage imageWithData:imageData];
    
    //模式
    [filter setValue:beginImage forKey:kCIInputImageKey];
    
    //渲染并输出CIImage
    CIImage *outputImage = [filter outputImage];
    
    //获取绘制上下文
    CIContext *context = [CIContext contextWithOptions:nil];
    
    //创建CGImage句柄
    CGImageRef cgimg = [context createCGImage: outputImage fromRect:[beginImage extent]];
    
    //获取图片
    UIImage *newImage = [UIImage imageWithCGImage:cgimg];
    
    //释放CGImage句柄
    CGImageRelease(cgimg);
    
    //赋值img
    _imgView_Top.image = newImage;
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

下图为模拟器效果

给图片增加高斯模糊效果_第1张图片



demo链接 :高斯模糊--司小文(提取码:978c)


感谢观看,学以致用更感谢。




你可能感兴趣的:(iOS-功能)