我正在尝试将UIImageView的image属性设置为使用CoreImage模糊化的图像。该代码可完美处理未过滤的图像,但是当我将背景图像设置为过滤后的图像时,contentMode似乎不再适用于UIImageView-而不是宽高比,图像会垂直拉伸(stretch)。除了在代码中设置contentMode之外,我还在 Storyboard 上进行了设置,但结果是相同的。

我正在使用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,以及如何解决该问题?

最佳答案

解决方法是更换您的生产线:

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
}

关于ios - UIImageView contentMode在模糊效果应用程序后无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32596264/

10-12 05:32