菜鸟一只,早就有写博客的打算了,可是一直不知道从什么开始写起,这个状态持续了快半年了······最近越来越迫切的感觉要把平时开发和自己学到的一些东西记录下来,于是打算在这里开写了!同时和大家一起分享!

        平时会看到很多iOS App会用到一些模糊半透明的效果,其实这种效果的实现是先在原屏幕特定区域截图,得到UIImage,处理这个UIImage得到想要的效果。然后把这个处理后的UIImage添加到当前的View上。

        由此可见,做这个半透明模糊效果的的前提是截图,那么下面这个方法可以实现这个功能:

- (UIImage *)viewSnapshot:(UIView *)view withInRect:(CGRect)rect;{    UIGraphicsBeginImageContext(view.bounds.size);    [view.layer renderInContext:UIGraphicsGetCurrentContext()];    UIImage *p_w_picpath = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    p_w_picpath = [UIImage p_w_picpathWithCGImage:CGImageCreateWithImageInRect(p_w_picpath.CGImage,rect)];    return p_w_picpath;}

        这里面有2个参数view和rect,view:即在这个view的整个截图,rect:获取当前view的截图之后,在此基础之上获取rect范围的截图。

        这样调用就可以获取testView的截图:

UIImage *shotImage = [[UIImage alloc] init];[self viewSnapshot:testView withInRect:testView.bounds];

        在有些情况下只截取一个View的图像是无法满足我们的需求的。假如我们想获取整个屏幕的截图,如果手机当前页面存在一个导航栏的话,截取self.view是无法将导航栏也截取进来的,下面这个方法可以解决这个问题:

-(void)fullScreenshots{    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;    UIWindow *screenWindow = appDelegate.window;    UIGraphicsBeginImageContext(screenWindow.frame.size);    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];    UIImage *p_w_picpath = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    UIImageWriteToSavedPhotosAlbum(p_w_picpath, nil, nil, nil); //将截图存入相册}

        方法最后一句代码是将获取到的截图保存到手机本地的相册,当获取到想要的截图之后,就可以对截取到的图片进行处理了,处理图片这里我使用GPUImage这个开源框架,在GitHub上非常受欢迎。建议用CoCoaPods将框架引人到工程。

        首先初始化一个GPUImgeView:

 GPUImageView *testView = [[GPUImageView alloc] initWithFrame:self.view.bounds]; testView.clipsToBounds = YES; testView.layer.contentsGravity = kCAGravityTop;

        然后初始化一个滤镜:

 GPUImageGaussianBlurFilter *blurFilter = [[GPUImageGaussianBlurFilter alloc] init]; blurFilter.blurRadiusInPixels = 5.0f;

        最后初始化一个GPUImagePicture:

 GPUImagePicture *picture = [[GPUImagePicture alloc] initWithImage:[self fullScreenshots]]; [picture addTarget:blurFilter]; [blurFilter addTarget:testView]; [picture processImageWithCompletionHandler:^{ [blurFilter removeAllTargets]; }];

        当我们执行完上述代码之后,带有模糊效果的图片就会呈现在testView上了。