高斯模糊效果的簡單實現

這裏簡單介紹一下高斯模糊效果.這裏介紹的是coreImage,原理很簡單就是抓取現在當前的image,然後設置高斯模糊.

首先是獲取當前的image:(兩種方法)

方法一:

- (UIImage *)snapshot:(UIView *)view

{

    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);

    

    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];

    

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    

    UIGraphicsEndImageContext();

    

    return image;

}

方法二

- (UIImage *)imageOfView:(UIView *)view

{

    UIGraphicsBeginImageContext(view.bounds.size); //currentView 當前的view

    

    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    

    UIImage *screenImage = UIGraphicsGetImageFromCurrentImageContext();

    

    UIGraphicsEndImageContext();

    

    return screenImage;

}

//接下來這個方法就是獲取全屏截圖,將全屏圖片高斯模糊並添加到一個view上

- (void)addToView:(UIView *)view{

    UIImage *screenImage = [self snapshot:view];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kwidth, kheight)];

    imageView.userInteractionEnabled = YES;

    [view addSubview:imageView];

    

    CIContext *context = [CIContext contextWithOptions:nil];

    UIImage *oldImage = screenImage;

    CIImage *inputImage = [[CIImage alloc] initWithImage:oldImage];

    // create gaussian blur filter

    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];

    [filter setValue:inputImage forKey:kCIInputImageKey];

    [filter setValue:[NSNumber numberWithFloat:20.0] forKey:@"inputRadius"];

    // blur image

    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];

    UIImage *image = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);

    imageView.image = image;

}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章