如何在 Swift 中添加半径为 2pt 的模糊?

Doe*_*Doe 0 ios swift uiblureffect

我想创造这样的东西:

在此处输入图片说明

我试过这个:

var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
var blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
view.addSubview(blurEffectView)
Run Code Online (Sandbox Code Playgroud)

但这会造成非常暗的模糊。但我需要半径为 2pt 的完全暗模糊(黑色)。

我可以在 Swift 中实现吗?

bey*_*ulf 5

您无法控制 a 的模糊半径UIVisualEffectView。您可以通过对要模糊的视图进行快照并将 CoreImage 的“CIGaussianBlur”过滤器应用于该快照,然后在UIImageView要模糊的视图的正上方显示模糊图像来实现您想要的效果。有了CIGaussianBlur你可以申请一个模糊半径为任意长度。

您可以使用扩展名UIView来使这更方便:

extension UIView
{
    func snapshotView(scale scale: CGFloat = 0.0, isOpaque: Bool = true) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, opaque, scale)
        self.drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

    func blur(blurRadius blurRadius: CGFloat) -> UIImage?
    {
        guard let blur = CIFilter(name: "CIGaussianBlur") else { return nil }

        let image = self.snapshotView(scale: 1.0, isOpaque: true)
        blur.setValue(CIImage(image: image), forKey: kCIInputImageKey)
        blur.setValue(blurRadius, forKey: kCIInputRadiusKey)

        let ciContext  = CIContext(options: nil)

        let result = blur.valueForKey(kCIOutputImageKey) as! CIImage!

        let boundingRect = CGRect(x: 0,
                                  y: 0,
                                  width: frame.width,
                                  height: frame.height)

        let cgImage = ciContext.createCGImage(result, fromRect: boundingRect)

        return UIImage(CGImage: cgImage)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以添加一个半透明的叠加来确定模糊的暗度,例如:

let overlay = UIView()
overlay.frame = view.bounds
overlay.backgroundColor = UIColor(white: 0.0, alpha: 0.30)
viewIWantToBlur.addSubview(overlay)
let image = viewIWantToBlur.blur(blurRadius: 2.0)
imageView.image = image
Run Code Online (Sandbox Code Playgroud)

有关此方法的更多信息和更强大的工作示例,您可以在此处查看。您应该知道这是性能密集型的。