你可以制作自己的
模糊标签
,以实现文本的模糊/非模糊。通过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
}
}
提示:请根据您的要求改进此组件(例如,如果已经模糊,请避免再次模糊,或者如果文本更改,则可以删除当前的模糊并重新应用模糊)。
另外需要考虑的是,将模糊应用于某些内容会导致其内容溢出,因此要么将clipsToBounds=false
应用于BlurredLabel
,要么找到其他实现视觉效果的方法,以避免模糊图像看起来不在与之前未模糊的标签文本相同的位置。
要使用它,您可以简单地创建一个BlurredLabel
:
let blurredLabel = BlurredLabel()
blurredLabel.text = "56.00 €"
在点击某个按钮时,您可以通过blurredLabel.blur()
进行模糊操作,并通过blurredLabel.unblur()
取消模糊。
使用blur()
方法并将模糊半径设为2.5,可以获得以下输出:
![](https://istack.dev59.com/Wwbv9.webp)
要了解更多高斯模糊的信息,可以查阅维基百科上的相关文章:https://en.wikipedia.org/wiki/Gaussian_blur