write a function that writes text into an image in swift

You can use the Core Graphics framework to write text into an image in Swift. Here is an example function:

main.swift
func drawText(_ text: String, inImage image: UIImage, atPoint point: CGPoint, textColor: UIColor, font: UIFont) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(image.size, false, 0.0)
    image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
    
    let style = NSMutableParagraphStyle()
    style.alignment = NSTextAlignment.center
    
    let attributes = [
        NSAttributedString.Key.font: font,
        NSAttributedString.Key.foregroundColor: textColor,
        NSAttributedString.Key.paragraphStyle: style
    ]
    let textSize = text.size(withAttributes: attributes as [NSAttributedString.Key : Any])
    
    let rect = CGRect(x: point.x - textSize.width / 2, y: point.y - textSize.height / 2, width: textSize.width, height: textSize.height)
    text.draw(in: rect, withAttributes: attributes as [NSAttributedString.Key : Any])
    
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return newImage
}
1011 chars
23 lines

This function takes in a string of text to be drawn, an image to draw on, a point to draw the text at, a text color, and a font. It returns a new image with the text drawn on it.

Note that the text.draw(in:rect:withAttributes:) method is used to draw the text into a rectangular area with the provided attributes. You can adjust the size and positioning of the text by modifying the rect parameter.

related categories

gistlibby LogSnag