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

Swift实现UITextView中图片附件圆角设置方法求助

为UITextView中的NSTextAttachment图片添加圆角

你无法直接给NSTextAttachment设置圆角,核心解决思路是先处理图片本身,生成带圆角的UIImage实例,再赋值给附件。以下是具体实现方案:

1. 封装UIImage圆角生成扩展

先写一个可复用的UIImage扩展方法,用来生成指定圆角半径的图片:

extension UIImage {
    func withRoundedCorners(radius: CGFloat) -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
        draw(in: rect)
        let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return roundedImage
    }
}

2. 修改原有代码实现圆角效果

替换你代码中直接赋值图片的逻辑,改用处理过圆角的图片:

@IBOutlet weak var informacionTextView: UITextView!

// 配置居中段落样式
let imageStyle = NSMutableParagraphStyle()
imageStyle.alignment = .center

// 创建图片附件
let textImage = NSTextAttachment()
// 加载原图并生成带圆角的图片(这里设置圆角半径为10,可按需调整)
if let originalImage = UIImage(named: "iconapp.png"), let roundedImage = originalImage.withRoundedCorners(radius: 10) {
    textImage.image = roundedImage
}
// 调整图片显示尺寸
textImage.bounds = CGRect(x: 0, y: 0, width: 111, height: 111)

// 构建带附件的富文本并添加居中样式
let attrStringWithImage = NSMutableAttributedString(attachment: textImage)
attrStringWithImage.addAttribute(NSAttributedString.Key.paragraphStyle, value: imageStyle, range: NSRange(location: 0, length: attrStringWithImage.length))

// 组装最终文本并展示
let informacionCompleta = NSMutableAttributedString()
informacionCompleta.append(attrStringWithImage)
informacionTextView.attributedText = informacionCompleta

补充说明

  • 若需要圆形图片,只需将圆角半径设置为图片边长的一半(比如这里的111/2=55.5)即可。
  • 扩展方法中使用UIGraphicsBeginImageContextWithOptions能保证生成的圆角图片适配不同屏幕分辨率,避免模糊。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:58:31