How can I round the corners of an image attachment displayed in a UITextView using Swift?

158 Views Asked by At

I am writing on this forum to receive help, I am writing an app on Swift for iPhone and I have created a textview to present some information to end user BUT I have included a picture as an attachment and the issue here is I don't know how to round all corners of that attachment picture. Below is my code:

// Outlet created:
@IBOutlet weak var informacionTextView: UITextView!

// Image Creation.
// center Paragraph.
let imageStyle = NSMutableParagraphStyle()
imageStyle.alignment = .center

// create attachment attrStringWithImage 
let textImage = NSTextAttachment()
textImage.image = UIImage(named: "iconapp.png")!
let attrStringWithImage = NSAttributedString(attachment: textImage).mutableCopy() as! NSMutableAttributedString
// Resize
textImage.bounds = CGRectMake(0, 0, 111, 111)

// Adding Center.
let length2 = attrStringWithImage.length
attrStringWithImage.addAttribute(NSAttributedString.Key.paragraphStyle, value: imageStyle, range: NSRange(location: 0, length: length2))

// Var creation to display.
let informacionCompleta = NSMutableAttributedString()

informacionCompleta.append(attrStringWithImage)

informacionTextView.attributedText = informacionCompleta

Would you please share any idea to make the iconapp appear on textview with rounded corners?

I tried to use some code but I always failed.

I am expecting to receive help.

1

There are 1 best solutions below

0
Vollan On

Here is an extension that rounds corners of UIImages.

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

Used: textImage.image = UIImage(named: "iconapp.png")!.roundedImage(withCornerRadius: 10)