- 我在您的代码中看到的第一件事是您没有在异步任务中应用过滤器。模糊图像需要时间,所以如果你不想冻结你应该使用的主线程:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//blur the image in a second thread
dispatch_async(dispatch_get_main_queue(), ^{
//set the blurred image to your imageView in the main thread
});
});
- 要反转原始图像,您只需将模糊副本放在出现在原始图像上的其他 imageView 中。在我的情况下,原始图像不是 imageView,而是视图本身。所以我只在我的视图中添加一个 imageView 来设置模糊图像,并在我想反转时设置为 nil。
- 最后,如果您想在设置模糊图像时避免眨眼,您可以在动画中使用 alpha 来进行软过渡:
[self.blurredImageView setAlpha: 0.0]; //make the imageView invisible
[self.blurredImageView setImage:blurredImage];
//and after set the image, make it visible slowly.
[UIView animateWithDuration:0.5 delay:0.1
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
[self.blurredImageView setAlpha: 1.0];
}
completion:nil];
- (void)makeBlurredScreenShot{
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *imageView = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CIContext *context = [CIContext contextWithOptions:nil];
CIImage *sourceImage = [CIImage imageWithCGImage:imageView.CGImage];
// Apply clamp filter:
// this is needed because the CIGaussianBlur when applied makes
// a trasparent border around the image
NSString *clampFilterName = @"CIAffineClamp";
CIFilter *clamp = [CIFilter filterWithName:clampFilterName];
if (!clamp)
return;
[clamp setValue:sourceImage forKey:kCIInputImageKey];
CIImage *clampResult = [clamp valueForKey:kCIOutputImageKey];
// Apply Gaussian Blur filter
NSString *gaussianBlurFilterName = @"CIGaussianBlur";
CIFilter *gaussianBlur = [CIFilter filterWithName:gaussianBlurFilterName];
if (!gaussianBlur)
return;
[gaussianBlur setValue:clampResult forKey:kCIInputImageKey];
[gaussianBlur setValue:[NSNumber numberWithFloat:8.0] forKey:@"inputRadius"];
CIImage *gaussianBlurResult = [gaussianBlur valueForKey:kCIOutputImageKey];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CGImageRef cgImage = [context createCGImage:gaussianBlurResult fromRect:[sourceImage extent]];
UIImage *blurredImage = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
dispatch_async(dispatch_get_main_queue(), ^{
[self.blurredImageView setAlpha: 0.0];
[self.blurredImageView setImage:blurredImage];
[UIView animateWithDuration:0.5 delay:0.1
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
[self.blurredImageView setAlpha: 1.0];
}
completion:nil];
});
});
}
- (void)removeBlurredScreenShot{
[UIView animateWithDuration:0.5 delay:0.1
options:UIViewAnimationOptionCurveEaseInOut
animations:^{
[self.blurredImageView setAlpha: 0.0];
}
completion:^(BOOL finished) {
[self.blurredImageView setImage:nil];
}];
}