You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何模糊UITextView使其文本可识别但无法阅读?

解决UITextView文本模糊问题

你之前的错误是用UIVisualEffectView直接覆盖在UITextView上,这种方式只会模糊视图的背景内容,导致文本被遮挡,呈现出灰色块。要实现文本本身模糊、可识别为文字但无法阅读的效果,需要对文本的渲染过程添加模糊处理,而非覆盖模糊层。

方案:自定义模糊文本UITextView子类

通过重写draw(_:)方法,先将文本绘制到离屏上下文,再对绘制结果应用高斯模糊滤镜,最后将模糊后的内容绘制到视图上。

import UIKit
import CoreImage

class BlurredTextView: UITextView {
    // 控制模糊程度,可根据需求调整(建议2-5之间)
    var blurRadius: CGFloat = 3.0
    
    override func draw(_ rect: CGRect) {
        // 1. 创建离屏绘图上下文
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        
        // 2. 先将原文本绘制到离屏上下文
        super.draw(rect)
        
        // 3. 获取绘制好的文本图片并转为CIImage
        guard let textImage = UIGraphicsGetImageFromCurrentImageContext(),
              let ciTextImage = CIImage(image: textImage) else {
            // 若处理失败,直接绘制原文本
            super.draw(rect)
            return
        }
        
        // 4. 应用高斯模糊滤镜
        let blurFilter = CIFilter(name: "CIGaussianBlur")!
        blurFilter.setValue(ciTextImage, forKey: kCIInputImageKey)
        blurFilter.setValue(blurRadius, forKey: kCIInputRadiusKey)
        
        // 5. 将模糊后的CIImage转为CGImage
        guard let blurredCI = blurFilter.outputImage,
              let blurredCG = CIContext(options: nil).createCGImage(blurredCI, from: blurredCI.extent) else {
            super.draw(rect)
            return
        }
        
        // 6. 将模糊后的图片绘制到当前视图上下文
        UIGraphicsGetCurrentContext()?.draw(blurredCG, in: bounds)
    }
}

使用方式

替换原有的UITextView为自定义子类即可:

private lazy var textView: BlurredTextView = {
    let textView = BlurredTextView()
    textView.blurRadius = 3.5 // 调整模糊程度
    textView.text = "这里是需要模糊的文本内容"
    textView.font = UIFont.systemFont(ofSize: 16)
    textView.backgroundColor = .white
    // 其他UITextView配置
    return textView
}()

可选:编辑时取消模糊

如果需要在编辑文本时恢复清晰状态,可添加代理方法控制模糊开关:

extension BlurredTextView: UITextViewDelegate {
    var isBlurred: Bool = true {
        didSet { setNeedsDisplay() }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        delegate = self
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        delegate = self
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        isBlurred = false
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        isBlurred = true
    }
    
    override func draw(_ rect: CGRect) {
        if !isBlurred {
            super.draw(rect)
            return
        }
        // 原模糊绘制代码...
    }
}

内容的提问来源于stack exchange,提问作者ocuke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:02:51