向标签添加模糊视图?

Add blur view to label?

如何为标签添加模糊视图?标签位于 UIImage 的前面,我希望标签的背景模糊,以便用户可以更好地阅读文本。我在标签的边界内获得了模糊效果,但文本本身消失了(也许也会变得模糊,我不知道为什么)。我还尝试以编程方式添加标签,但没有成功。我感谢任何形式的帮助!

let blur = UIBlurEffect(style: .Light)
    let blurView = UIVisualEffectView(effect: blur)

    blurView.frame = findATeamLabel.bounds
    findATeamLabel.addSubview(blurView)

您可以尝试将其发送到标签视图层次结构的后面。尝试

findATeamLabel.sendSubviewToBack(blurView)

我通过在标签后面添加一个视图来让它工作(标签不在那个视图里面,就在它前面)。然后我给视图添加了模糊效果...我仍然认为应该有更简单的方法。

您可以制作自己的 BlurredLabel,它可以 blur/unblur 其文本。通过 CoreImage 模糊过滤器,您可以获取标签的文本,将其模糊成图像,然后将该图像显示在标签的顶部。

class BlurredLabel: UILabel {

    func blur(_ blurRadius: Double = 2.5) {        
        let blurredImage = getBlurryImage(blurRadius)
        let blurredImageView = UIImageView(image: blurredImage)
        blurredImageView.translatesAutoresizingMaskIntoConstraints = false
        blurredImageView.tag = 100
        blurredImageView.contentMode = .center
        blurredImageView.backgroundColor = .white
        addSubview(blurredImageView)
        NSLayoutConstraint.activate([
            blurredImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            blurredImageView.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
    }

    func unblur() {
        subviews.forEach { subview in
            if subview.tag == 100 {
                subview.removeFromSuperview()
            }
        }
    }

    private func getBlurryImage(_ blurRadius: Double = 2.5) -> UIImage? {
        UIGraphicsBeginImageContext(bounds.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        guard let image = UIGraphicsGetImageFromCurrentImageContext(),
            let blurFilter = CIFilter(name: "CIGaussianBlur") else {
            UIGraphicsEndImageContext()
            return nil
        }
        UIGraphicsEndImageContext()

        blurFilter.setDefaults()

        blurFilter.setValue(CIImage(image: image), forKey: kCIInputImageKey)
        blurFilter.setValue(blurRadius, forKey: kCIInputRadiusKey)

        var convertedImage: UIImage?
        let context = CIContext(options: nil)
        if let blurOutputImage = blurFilter.outputImage,
            let cgImage = context.createCGImage(blurOutputImage, from: blurOutputImage.extent) {
            convertedImage = UIImage(cgImage: cgImage)
        }

        return convertedImage
    }
}

PS:请确保根据您的要求改进此组件(例如,如果已经模糊,请避免模糊,或者您可以删除当前模糊并应用如果文本已更改,则再次模糊)。

PSPS:还要考虑到对某物应用模糊会使其内容渗出,因此要么将 clipsToBounds = false 设置为BlurredLabel 或找出其他方法来实现您的视觉效果,以避免模糊图像看起来与之前的标签未模糊文本不在同一位置。

要使用它,您只需创建一个 BlurredLabel:

let blurredLabel = BlurredLabel()
blurredLabel.text = "56.00 €"

点击一些按钮,也许您可​​以实现从 blurredLabel.blur() 开始的模糊和从 blurredLabel.unblur() 开始的不模糊。

这是 通过 blurRadius 2.5 的 blur() 实现的输出:

要了解更多关于高斯模糊的信息,维基百科上有一篇很好的文章:https://en.wikipedia.org/wiki/Gaussian_blur