iOS程序猿之毛玻璃效果

来源:互联网 发布:中国传媒大学网络教育 编辑:程序博客网 时间:2024/05/07 02:29

毛玻璃效果

在iOS开发中有时会遇到给视图或图片设置模糊,来提升用户体验,iOS7之后半透明模糊效果得到大范围的应用,下面整理几种毛玻璃效果的代码

1.UIToolbar

苹果在iOS7.0之后,很多系统界面都使用了毛玻璃效果,增加了界面的美观性,比如通知中心界面;其实在iOS7.0(包括)之前还是有系统的类可以实现毛玻璃效果的, 就是 UIToolbar这个类

iOS7.0 毛玻璃的样式(枚举) UIBarStyleDefault = 0, UIBarStyleBlack = 1,UIBarStyleBlackOpaque = 1, // Deprecated. Use UIBarStyleBlack UIBarStyleBlackTranslucent = 2, // Deprecated. Use UIBarStyleBlack and set the translucent property to YESUIImageView *bgImgView = [[UIImageView alloc] initWithFrame:self.view.bounds]; bgImgView.image = [UIImage imageNamed:@"huoying4.jpg"]; [self.view addSubview:bgImgView]; UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, bgImgView.frame.size.width*0.5, bgImgView.frame.size.height)]; toolbar.barStyle = UIBarStyleBlackTranslucent; [bgImgView addSubview:toolbar];

2.UIVisualEffectView

在iOS8.0之后,苹果新增了一个类UIVisualEffectView,通过这个类来实现毛玻璃效果与上面的UIToolbar一样,而且效率也非常之高,使用也是非常简单,几行代码搞定. UIVisualEffectView是一个抽象类,不能直接使用,需通过它下面的三个子类来实现(UIBlurEffect, UIVisualEffevt, UIVisualEffectView);

子类UIBlurEffect只有一个类方法,用来快速创建一个毛玻璃效果,参数是一个枚举,用来设置毛玻璃的样式,而UIVisualEffectView则多了两个属性和两个构造方法,用来快速将创建的毛玻璃添加到这个UIVisualEffectView上.

特别注意: 这个类是iOS8.0之后才适用, 所以如果项目要兼容iOS7.0的话, 还是要考虑其它的方法了.

iOS8.0 毛玻璃的样式(枚举) UIBlurEffectStyleExtraLight, UIBlurEffectStyleLight, UIBlurEffectStyleDark UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]; UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; effectView.frame = CGRectMake(0, 0, bgImgView.frame.size.width*0.5, bgImgView.frame.size.height); [bgImgView addSubview:effectView];

3.CoreImage:

iOS5.0之后就出现了Core Image的API,Core Image的API被放在CoreImage.framework库中, 在iOS和OS X平台上,Core Image都提供了大量的滤镜(Filter),在OS X上有120多种Filter,而在iOS上也有90多。

+(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;}

4.GPUImage (第三方)

除了苹果官方提供的之外,第三方也有这方面图片处理的工具。一个叫Brad Larson的老兄就搞了一套叫做GPUImage的开源库。同样的,里面提供了很多Filter。

GPUImageGaussianBlurFilter * blurFilter = [[GPUImageGaussianBlurFilter alloc] init];blurFilter.blurRadiusInPixels = 2.0;UIImage * image = [UIImage imageNamed:@"xxx"];UIImage *blurredImage = [blurFilter imageByFilteringImage:image];








0 0
原创粉丝点击