79339107

Date: 2025-01-08 12:21:27
Score: 1.5
Natty:
Report link

You can implement it like this:

Effect screenshots enter image description here


let view = UITextView()
view.attributedText = testAttributedString()
return view

func testAttributedString() -> NSAttributedString {
    let test = NSMutableAttributedString()
    test.append(.init(string: "How"))
    test.append("are".generateImage(.init(width: 60, height: 30)))
    test.append(.init(string: "you"))
    return test
}

extension String {
    func generateImage(_ size: CGSize, 
                       textFont: UIFont = .systemFont(ofSize: 16),
                       textColor: UIColor = .white, 
                       fillColor: UIColor = .brown) -> NSAttributedString {
        let format = UIGraphicsImageRendererFormat()
        format.scale = UIScreen.main.scale
        let render = UIGraphicsImageRenderer(size: size, format: format)
        
        let image = render.image { context in
            let ellipsePath = UIBezierPath(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: size.height / 2).cgPath
            context.cgContext.setFillColor(fillColor.cgColor)
            context.cgContext.addPath(ellipsePath)
            context.cgContext.fillPath()
            let attributed = NSAttributedString(string: self, attributes: [.font: textFont, .foregroundColor: textColor])
            let textSize = attributed.size()
            attributed.draw(at: CGPoint(x: (size.width - textSize.width) / 2, y: (size.height - textSize.height) / 2))
        }
        let attachment = NSTextAttachment(data: nil, ofType: nil)
        attachment.image = image
        attachment.bounds = .init(x: 0, y: -9.3125, width: size.width, height: size.height)
        attachment.lineLayoutPadding = 5
        return .init(attachment: attachment)
    }
}
Reasons:
  • Blacklisted phrase (1): enter image description here
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: saucym