Gaussian Blur Over Image - iOS 8

倾然丶 夕夏残阳落幕 提交于 2019-12-05 02:42:44

问题


I have a moving background image and I want to blur the bottom part of it out. I would do it with just photoshop but since the image moves, it wouldn't work very well.

Here is what I mean (look at the bottom of the image) :

So basically like the effect the dock has on the iPhone. I'm using iOS 8 but not Swift.


回答1:


I have done a small example based on the photo you have there. My algorithm is as follows:

  • Extract a portion of image from bottom.
  • Apply gaussian filter to it and blur it.
  • Then, create a new image context, draw original image on it.
  • Then, draw the blurred portion of the image to place it exactly over the original image.
  • Extract the new image from the context.

Here is a source code for doing so,

 @implementation ViewController


- (void)viewDidLoad{

  [super viewDidLoad];
  UIImageView *imageView = [[UIImageView alloc] init];
  imageView.frame = self.view.bounds;
  [self.view  addSubview:imageView];
  imageView.contentMode = UIViewContentModeScaleAspectFit;
  UIImage *image = [UIImage imageNamed:@"monogram.jpg"];
  imageView.image = [self imageWithBlurredImageWithImage: image andBlurInsetFromBottom: 200 withBlurRadius:3];
}

- (UIImage*)imageWithBlurredImageWithImage:(UIImage*)image andBlurInsetFromBottom:(CGFloat)bottom withBlurRadius:(CGFloat)blurRadius{
  UIGraphicsBeginImageContext(image.size);
  CGContextRef context =  UIGraphicsGetCurrentContext();
  CGContextScaleCTM(context, 1, -1);
  CGContextTranslateCTM(context, 0, -image.size.height);
  CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, image.size.height), image.CGImage);
  CGContextDrawImage(context, CGRectMake(0, 0, image.size.width, bottom), [self blurImage: image withBottomInset: bottom blurRadius: blurRadius].CGImage);
  image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return image;
}

- (UIImage*)blurImage:(UIImage*)image withBottomInset:(CGFloat)inset blurRadius:(CGFloat)radius{

  image =  [UIImage imageWithCGImage: CGImageCreateWithImageInRect(image.CGImage, CGRectMake(0, image.size.height - inset, image.size.width,inset))];

  CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];
  CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
  [filter setValue:ciImage forKey:kCIInputImageKey];
  [filter setValue:@(radius) forKey:kCIInputRadiusKey];

  CIImage *outputCIImage = filter.outputImage;
  CIContext *context = [CIContext contextWithOptions:nil];

  return [UIImage imageWithCGImage: [context createCGImage:outputCIImage fromRect:ciImage.extent]];

}
@end

And here is the screenshot of the result.



来源:https://stackoverflow.com/questions/25897867/gaussian-blur-over-image-ios-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!