beg*_*r_T 5 label blur ios swift
如何将模糊视图添加到标签?标签位于UIImage前面,我希望标签的背景模糊,以便用户可以更好地阅读文本.我在标签的边界内得到了模糊效果,但是文本本身消失了(可能也会变得模糊,为什么会这样).我还尝试以编程方式添加标签,但我没有让它工作.我感谢任何帮助!
let blur = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: blur)
blurView.frame = findATeamLabel.bounds
findATeamLabel.addSubview(blurView)
Run Code Online (Sandbox Code Playgroud)
您可以制作自己的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
}
}
Run Code Online (Sandbox Code Playgroud)
PS:请确保根据您的要求改进此组件(例如,如果已经模糊,则避免模糊,或者如果文本已更改,您可以删除当前模糊并再次应用模糊)。
PSPS:还要考虑到对某物应用模糊会使其内容流血,所以要么设置clipsToBounds = false
为BlurredLabel
要么找出其他方法来完成您的视觉效果,以避免模糊图像看起来与未模糊标签的位置不在同一位置之前的文字。
要使用它,您只需创建一个BlurredLabel
:
let blurredLabel = BlurredLabel()
blurredLabel.text = "56.00 €"
Run Code Online (Sandbox Code Playgroud)
在某些按钮上,也许您可以实现从 开始的模糊blurredLabel.blur()
和从 开始的去模糊blurredLabel.unblur()
。
这是blur()
通过 ablurRadius
为 2.5实现的输出:
要阅读有关高斯模糊的更多信息,维基百科上有一篇很好的文章:https : //en.wikipedia.org/wiki/Gaussian_blur
您可以尝试将其发送到标签视图层次结构的后面。尝试
findATeamLabel.sendSubviewToBack(blurView)
归档时间: |
|
查看次数: |
2334 次 |
最近记录: |