UIImageView contentMode not working after blur effect application
Asked Answered
H

1

5

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?

Heir answered 15/9, 2015 at 21:49 Comment(0)
K
7

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
}
Kreisler answered 16/9, 2015 at 1:55 Comment(1)
Thank you! Why does it need to be made into a CGImage before UIImage?Heir

© 2022 - 2024 — McMap. All rights reserved.