iOS模糊效果

实现模糊效果的方式有好几种,这里说明其中两种。

1.毛玻璃


iOS模糊效果_第1张图片
屏幕快照 2016-12-29 22.18.50.png
    UIImageView * imgView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 300, 300)];
    imgView.image = [UIImage imageNamed:@"img"];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview: imgView];
    
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = CGRectMake(0, 0, bgImgView.frame.size.width*0.5, imgView.frame.size.height);
    [bgImgView addSubview:effectView];

2.高斯模糊,将图片处理成高斯模糊。

iOS模糊效果_第2张图片
屏幕快照 2016-12-29 22.24.31.png
{
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 300, 300)];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imgView];

    UIImage *img = [UIImage imageNamed:@"img"];
    UIImage *blurImg = [self blur:img];
    imgView.image = blurImg;
}

//生成一张毛玻璃图片
- (UIImage*)blur:(UIImage*)theImage
{
    CGFloat num = 10.0; //模糊度
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:theImage.CGImage];
    
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat:num] forKey:@"inputRadius"];
    
    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];
    
    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    
    return returnImage;
}

值得一提的是,将图片处理成高斯模糊对性能需求大一些,如果大量的处理高斯模糊会造成卡顿,可放线程或其他方式解决。

附送一个view转换成image的方法

//将页面view转换成image
- (UIImage *)getImageWithTheView:(UIView *)theView
{
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size, YES, 0);
    [theView drawViewHierarchyInRect:theView.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

你可能感兴趣的:(iOS模糊效果)