iOS Swift - 在Swift 3中实现Sketch风格的高斯模糊效果

3
我是新手,正在学习Swift。我已经使用高斯模糊效果在Sketch中创建了模糊的UI界面:
现在我想在UIImageView中实现这个效果。
是否可以使用视觉效果与模糊或CIFilter来实现相同的效果?(我尝试过,但没有成功。可能我错过了什么)
更新:
好的...感谢@firstinq。我打开了他的链接并意识到我使用的是kCIInputRadiusKey而不是inputRadius。现在在模拟器中我成功了,但在真正的iOS设备上还是有问题。
这是在模拟器(iPhone SE)中的截图:
但在真正的iOS设备(iPhone SE)上:
这是我的代码用于模糊图像:
   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
}

我在CollectionView项中使用了两张图片。其中一张图片是模糊的,另一张则是完全可见的。模糊的图片大小为125x125(高斯模糊会减小这个尺寸)。而可见的图片大小为50x50。这两张图片都有圆角,使它们呈圆形。


你尝试过使用GPUImage库吗? - girish_pro
在Core Image滤镜中还有一个高斯模糊滤镜:https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/filter/ci/CIGaussianBlur。你用过这个吗?给我们展示一些你尝试过的代码。 - firstinq
嗨,谢谢您的回复!我已经更新了问题并提供了更详细的信息,请查看。 - Mihir Joshi
1个回答

1

我不确定这是否符合您的要求,但高斯模糊实际上需要整个图像来创建一个新的图像。鉴于此,我推测您只想从imageView的内容视图中获取裁剪后的图像。 因此,首先您需要使用以下方法从视图中捕获图像:(我建议使用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
}

现在,您已经拥有所需的图像,这次我们应该对其进行高斯模糊处理: (同样,我更喜欢使用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)
}

回复内容存在敏感词^**$略微放大一些。

我也遇到了这个问题,我能够正确地实现这种效果,但是print方法太昂贵了,会减慢您在集合/表视图中滚动的速度。因此,我无法在我的项目中使用它,但是请随意在您的项目中尝试!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接