Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageView contentMode not working after blur effect application

I'm attempting to set the image property of a UIImageView to an image I'm blurring with CoreImage. The code works perfectly with an unfiltered image, but when I set the background image to the filtered image, contentMode appears to stop working for the UIImageView -- instead of aspect filling, the image becomes vertically stretched. In addition to setting contentMode in code, I also set it on the storyboard but the result was the same.

I'm using Swift 2 / Xcode 7.

func updateBackgroundImage(image: UIImage) {
    backgroundImage.contentMode = .ScaleAspectFill
    backgroundImage.layer.masksToBounds = true
    backgroundImage.image = blurImage(image)
}

func blurImage(image: UIImage) -> UIImage {
    let imageToBlur = CIImage(image: image)!

    let blurfilter = CIFilter(name: "CIGaussianBlur")!
    blurfilter.setValue(10, forKey: kCIInputRadiusKey)
    blurfilter.setValue(imageToBlur, forKey: "inputImage")

    let resultImage = blurfilter.valueForKey("outputImage") as! CIImage
    let croppedImage: CIImage = resultImage.imageByCroppingToRect(CGRectMake(0, 0, imageToBlur.extent.size.width, imageToBlur.extent.size.height))
    let blurredImage = UIImage(CIImage: croppedImage)

    return blurredImage
}

Why is filtering with CIImage causing my image to ignore contentMode and how do I fix the issue?

like image 445
Derrick Hunt Avatar asked Sep 15 '15 21:09

Derrick Hunt


1 Answers

Solution is to replace your line:

let blurredImage = UIImage(CIImage: croppedImage)

with these 2 lines:

let context = CIContext(options: nil)
let blurredImage = UIImage (CGImage: context.createCGImage(croppedImage, fromRect: croppedImage.extent))

So your full blurImage function would look like this:

func blurImage(image: UIImage) -> UIImage {
    let imageToBlur = CIImage(image: image)!

    let blurfilter = CIFilter(name: "CIGaussianBlur")!
    blurfilter.setValue(10, forKey: kCIInputRadiusKey)
    blurfilter.setValue(imageToBlur, forKey: "inputImage")

    let resultImage = blurfilter.valueForKey("outputImage") as! CIImage
    let croppedImage: CIImage = resultImage.imageByCroppingToRect(CGRectMake(0, 0, imageToBlur.extent.size.width, imageToBlur.extent.size.height))
    let context = CIContext(options: nil)
    let blurredImage = UIImage (CGImage: context.createCGImage(croppedImage, fromRect: croppedImage.extent))

    return blurredImage
}
like image 150
Elvin R. Avatar answered Nov 04 '22 21:11

Elvin R.