Reputation: 162
I'm new to Swift. I have created blurred UI in Sketch using Gaussian blur effect:
Now I want to implement this effect in UIImageView.
It is possible to use visual effect with blur or CIFilter to achieve same effect? (I've tried but didn't get it. May be I'm missing something)
Update:
Ok.. Thnks to @firstinq. I opened his link and realised that I was using kCIInputRadiusKey instead of inputRadius. Now I'm succeed in simulator but in real iOS device, it's still messed.
Here is the screenshot in simulator(iPhone SE):
But in real iOS device(iPhone SE):
Here is my code for blurring image:
func applyBlurEffect(image: UIImage) -> UIImage{
let imageToBlur = CIImage(image: image)
let blurfilter = CIFilter(name: "CIGaussianBlur")
blurfilter?.setValue(imageToBlur, forKey: "inputImage")
blurfilter?.setValue(13.4, forKey: "inputRadius")
let resultImage = blurfilter?.value(forKey: "outputImage") as! CIImage
let blurredImage = UIImage(ciImage: resultImage)
return blurredImage
}
I'm using two images in collectionView item. One image is blurred, And above it, another is fully visible. Blurred image is 125x125 sized (Gaussian blur will reduce this size). And visible image is 50x50 sized. Both images has corner radius to make them circular.
Upvotes: 3
Views: 2611
Reputation: 160
I don't know if that's what you want, but the gaussian blur actually takes the whole image to make a new one. Given this, I presume you want only the cropped image from the imageView's content view. So, first you have to capture the image from your view with:(I recommend using an extension of UIView)
public static func image(from view: UIView) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
view.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
So, now you have the desired Image, and this time we should gaussian blur it: (Again, I prefer using an extension, but this time of UIImage )
func getImageWithBlur() -> UIImage?{
let context = CIContext(options: nil)
guard let currentFilter = CIFilter(name: "CIGaussianBlur") else {
return nil
}
let beginImage = CIImage(image: self)
currentFilter.setValue(beginImage, forKey: kCIInputImageKey)
currentFilter.setValue(6.5, forKey: "inputRadius")
guard let output = currentFilter.outputImage, let cgimg = context.createCGImage(output, from: output.extent) else {
return nil
}
return UIImage(cgImage: cgimg)
}
Then you can setup another UIImageView with a smaller zPosition than the front UIImageView and with a little bit more of scale about the front UIImageView.
I was having this problem too, and I was able to get this effect right, but the print method is too expensive and it slows your scrolling through the collection/table View. So I was not able to use it in my project, but feel free to try it in yours!
Upvotes: 1