如何将模糊视图添加到标签?标签位于UIImage的前面,我希望标签的背景模糊,以便用户可以更好地阅读文本。我在标签的边界内获得了模糊效果,但是文本本身消失了(也许也变得模糊了,这是为什么)。我还尝试以编程方式添加标签,但没有成功。感谢您的帮助!
let blur = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = findATeamLabel.bounds
findATeamLabel.addSubview(blurView)
您可以尝试将其发送到标签的视图层次结构的后面。尝试
findATeamLabel.sendSubviewToBack(blurView)
我通过在标签后面添加一个视图来使它起作用(标签不在该视图内部,而是在其前面)。然后我在视图中添加了模糊效果...我仍然认为应该有一种更简单的方法。
您可以创建自己的BlurredLabel
,可以模糊/取消模糊其文本。通过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()
开始的模糊。
这是输出
用blur()
通过2.5的blurRadius
实现: