iOS开发之图片模糊效果的五种实现代码

2020-01-20 12:46:56王冬梅

前言

在iOS开发中我们经常会用到模糊效果使我们的界面更加美观,而iOS本身也提供了几种达到模糊效果的API,如:Core Image,使用Accelerate.Framework中的vImage API,在iOS 7之前系统的类提供UIToolbar,在iOS 8之后苹果新增加的一个类UIVisualEffectView;另外也有一些牛人写的第三方框架,如:GPUImage。本篇就针对这五种方式讲解一下具体的实现。

ios模糊效果,ios开发模糊效果,ios图片模糊效果

正文

下面就按照这五种方式,将其实现模糊效果的具体实现一一讲解一下:

在iOS 7之前系统的类提供UIToolbar来实现毛玻璃效果:


- (void)toolbarStyle{

 CGRect toolbarRect = CGRectMake(0, 0,ScreenW/2,ScreenH);
 UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:toolbarRect];
 /*
  * UIBarStyleDefault   = 0,
  * UIBarStyleBlack   = 1,
  * UIBarStyleBlackOpaque  = 1, // Deprecated. Use UIBarStyleBlack
  * UIBarStyleBlackTranslucent = 2, // Deprecated. Use UIBarStyleBlack and set the translucent property to YES
  */
 toolbar.barStyle = UIBarStyleBlack;

 [self.myImageView addSubview:toolbar];
}

在iOS 8之后苹果新增加了一个类UIVisualEffectView,通过这个类来实现毛玻璃效果:


- (void)uivisualEffectViewStyle{
 /* NS_ENUM_AVAILABLE_IOS(8_0)
  * UIBlurEffectStyleExtraLight,//额外亮度,(高亮风格)
  * UIBlurEffectStyleLight,//亮风格
  * UIBlurEffectStyleDark,//暗风格
  * UIBlurEffectStyleExtraDark __TVOS_AVAILABLE(10_0) __IOS_PROHIBITED __WATCHOS_PROHIBITED,
  * UIBlurEffectStyleRegular NS_ENUM_AVAILABLE_IOS(10_0), // Adapts to user interface style
  * UIBlurEffectStyleProminent NS_ENUM_AVAILABLE_IOS(10_0), // Adapts to user interface style

  */
 //实现模糊效果
 UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
 //毛玻璃视图
 UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];;
 effectView.frame = CGRectMake(0, 0, ScreenW/2, ScreenH);

 [self.myImageView addSubview:effectView];
}

iOS5.0之后就出现了Core Image的API,Core Image的API被放在CoreImage.framework库中, 在iOS和OS X平台上,Core Image都提供了大量的滤镜(Filter),在OS X上有120多种Filter,而在iOS上也有90多,Core Image设置模糊之后会在周围产生白边:


- (UIImage *)coreBlurImage:(UIImage *)image withBlurNumber:(CGFloat)blur{

 CIContext *context = [CIContext contextWithOptions:nil];
 CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];
 //设置filter
 CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
 [filter setValue:inputImage forKey:kCIInputImageKey];
 [filter setValue:@(blur) forKey:@"inputRadius"];
 //模糊图片
 CIImage *result = [filter valueForKey:kCIOutputImageKey];
 CGImageRef outImage = [context createCGImage:result fromRect:[result extent]];
 UIImage *blurImage = [UIImage imageWithCGImage:outImage];
 CGImageRelease(outImage);
 return blurImage;

}