前言
昨天看到一位簡(jiǎn)書(shū)作者的博客,寫(xiě)的是swift的版的模糊圖,正好我做的項(xiàng)目有這個(gè)需求,所以就翻譯了一版OC語(yǔ)言的
預(yù)覽圖

效果圖
#import "ViewController.h"
@interface ViewController ()
/** 展示圖片控件 */
@property (weak, nonatomic) IBOutlet UIImageView *imageview;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
/** 背景圖片 */
@property (strong, nonatomic) UIImageView *backgroundImageView;
/** 當(dāng)前圖片下標(biāo) */
@property (assign, nonatomic)NSInteger index;
@end
@implementation ViewController
- (IBAction)changeImage:(UIButton *)sender {
// 點(diǎn)擊切換圖片 偏移量為0
self.scrollview.contentOffset = CGPointZero;
_index++;
if (_index>5) {
_index = 1;
}
[self changeImageWithIndex];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 賦初值調(diào)用方法
_index = 1;
[self changeImageWithIndex];
}
/** 切換圖片方法 */
- (void)changeImageWithIndex{
[_imageview layoutIfNeeded];
NSString *str = [NSString stringWithFormat:@"%ld",_index];
self.imageview.image = [UIImage imageNamed:str];
// 調(diào)用高斯模糊方法
[self creatBlurBackgound:[UIImage imageNamed:str] view:_imageview blurRadius:50];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)creatBlurBackgound:(UIImage *)image view:(UIView *)view blurRadius:(CGFloat)blurRadius{
// 創(chuàng)建屬性
CIImage *cimage = [[CIImage alloc] initWithImage:image];
// 濾鏡效果 高斯模糊
CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
// 指定過(guò)濾照片
[filter setValue:cimage forKey:kCIInputImageKey];
// 模糊值
NSNumber *number = [NSNumber numberWithFloat:blurRadius];
// 指定模糊值
[filter setValue:number forKey:@"inputRadius"];
// 生成圖片
CIContext *context = [CIContext contextWithOptions:nil];
// 創(chuàng)建輸出
CIImage *result = [filter valueForKey:kCIOutputImageKey];
// 下面這一行的代碼耗費(fèi)時(shí)間內(nèi)存最多,可以開(kāi)辟線程處理然后回調(diào)主線程給imageView賦值
CGImageRef cgimage = [context createCGImage:result fromRect:result.extent];
UIImage *imagea = [UIImage imageWithCGImage:cgimage];
// 賦值圖片
self.backgroundImageView.image = imagea;
}
// 懶加載
- (UIImageView *)backgroundImageView{
if (!_backgroundImageView) {
// 獲取view寬高
CGFloat w = self.view.frame.size.width;
CGFloat h = self.view.frame.size.height;
// 4倍縮放
_backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-w/2, -h/2, w, 2*h)];
// 等比例填充模式
_backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
// 對(duì)其
_backgroundImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
// 添加到view上
[self.view insertSubview:_backgroundImageView belowSubview:_scrollview];
}
return _backgroundImageView;
}
@end
效果圖

高斯模糊圖
上代碼
scrollView和 button 都是為了換圖片看效果才加的,如果只需要模糊效果可以只創(chuàng)建一個(gè)imageView
gitHub:https://github.com/Lafree317/iOS-GaussImage
swift版博客地址:http://www.itdecent.cn/p/c9083a105921