UIImageView contentMode在模糊效果应用程序后无法正常工作

时间:2015-09-15 21:49:12

标签: ios swift uiimageview uiimage ciimage

我正在尝试将UIImageView的图像属性设置为我使用CoreImage模糊的图像。该代码与未经过滤的图像完美配合,但是当我将背景图像设置为过滤后的图像时,contentMode似乎停止为UIImageView工作 - 而不是填充方面,图像会垂直拉伸。除了在代码中设置contentMode之外,我还在故事板上设置它,但结果是一样的。

我正在使用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
}

为什么使用CIImage进行过滤导致我的图片忽略contentMode,如何解决此问题?

1 个答案:

答案 0 :(得分:6)

解决方案是替换你的行:

let blurredImage = UIImage(CIImage: croppedImage)

这两行:

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

所以你的完整blurImage函数看起来像这样:

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
}