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

如何为UILabel的部分文本背景设置图片?

当然可以实现!你目前用的NSAttributedStringKey.backgroundColor只能设置纯色背景,要给UILabel的富文本部分设置图片背景,得换个思路——下面给你两种iOS开发里常用的实用方案:

方案一:自定义UILabel重写绘制方法(推荐,灵活可控)

这个方法通过自定义UILabel,在绘制文本前先把图片绘制到目标文本对应的区域,能完美适配多行文本,还能自由调整图片和文本的间距。

首先创建一个自定义的UILabel子类:

class ImageBackgroundLabel: UILabel {
    // 存储需要设置背景图片的文本范围和对应图片
    var bgImageRange: NSRange?
    var bgImage: UIImage?
    
    override func drawText(in rect: CGRect) {
        // 校验必要参数,没有的话就走默认绘制逻辑
        guard let targetRange = bgImageRange, let image = bgImage, let attrText = attributedText else {
            super.drawText(in: rect)
            return
        }
        
        // 计算目标文本在Label中对应的实际绘制区域
        let textStorage = NSTextStorage(attributedString: attrText)
        let layoutManager = NSLayoutManager()
        textStorage.addLayoutManager(layoutManager)
        
        let textContainer = NSTextContainer(size: bounds.size)
        textContainer.lineFragmentPadding = 0
        textContainer.maximumNumberOfLines = numberOfLines
        textContainer.lineBreakMode = lineBreakMode
        layoutManager.addTextContainer(textContainer)
        
        var glyphRange = NSRange()
        layoutManager.characterRange(forGlyphRange: targetRange, actualGlyphRange: &glyphRange)
        let textRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer)
        
        // 绘制背景图片(这里可以通过inset调整图片和文本的间距)
        image.draw(in: textRect.insetBy(dx: 2, dy: 2))
        
        // 最后绘制文本,让文本叠在图片上面
        super.drawText(in: rect)
    }
}

接下来是使用示例:

// 创建自定义Label实例
let customLabel = ImageBackgroundLabel(frame: CGRect(x: 20, y: 100, width: 300, height: 100))
customLabel.numberOfLines = 0 // 支持多行

// 构建富文本
let originalText = "这是一段需要部分设置背景图片的示例文本"
let attrString = NSMutableAttributedString(string: originalText)
// 先设置基础文本属性(比如字体)
attrString.addAttribute(.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: originalText.count))
customLabel.attributedText = attrString

// 指定需要加背景图片的文本范围和图片
customLabel.bgImageRange = NSRange(location: 5, length: 8)
customLabel.bgImage = UIImage(named: "your_background_image")

// 添加到视图
view.addSubview(customLabel)
方案二:使用NSTextAttachment实现(适合单行简单场景)

如果你的文本是单行的,可以用NSTextAttachment来实现,把背景图片作为附件插入到文本中,再调整附件的位置让它成为文本的背景:

func getAttrStringWithBgImage(text: String, bgImage: UIImage, targetRange: NSRange) -> NSAttributedString {
    let attrString = NSMutableAttributedString(string: text)
    
    // 获取目标文本的字体信息,用来计算图片大小
    let targetFont = attrString.attribute(.font, at: targetRange.location, effectiveRange: nil) as? UIFont ?? UIFont.systemFont(ofSize: 16)
    let textSegment = (text as NSString).substring(with: targetRange)
    let textSize = textSegment.size(withAttributes: [.font: targetFont])
    
    // 创建附件并设置图片和尺寸
    let attachment = NSTextAttachment()
    attachment.image = bgImage
    // 调整bounds让图片刚好覆盖文本,y轴偏移让图片和文本对齐
    attachment.bounds = CGRect(x: 0, y: targetFont.descender, width: textSize.width, height: targetFont.lineHeight)
    
    // 创建带有附件的字符串,替换目标文本并插入原文本(调整基线偏移让文本叠在图片上)
    let targetAttrs = attrString.attributes(at: targetRange.location, effectiveRange: nil)
    let targetTextString = NSAttributedString(string: textSegment, attributes: targetAttrs)
    let offsetText = NSMutableAttributedString(attributedString: targetTextString)
    offsetText.addAttribute(.baselineOffset, value: targetFont.lineHeight, range: NSRange(location: 0, length: textSegment.count))
    
    attrString.replaceCharacters(in: targetRange, with: NSAttributedString(attachment: attachment))
    attrString.insert(offsetText, at: targetRange.location)
    
    return attrString
}

使用的时候直接调用这个方法生成富文本,赋值给普通UILabel即可。


内容的提问来源于stack exchange,提问作者Mahesh Prasad Mahalik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:33:14