Search code examples
iosswiftstringuikituiimage

How can I convert text (String) to image (UIImage) in Swift?


I did update of Xcode, cocoa pod, alamofire, alamofireimage today,

now I have a red marque on my code about text to image.

I am a beginner with coding.

func textToImage(drawText text: NSString, inImage image: UIImage, atPoint point: CGPoint) -> UIImage {
    let textColor = UIColor.red
    let textFont = UIFont(name: "Arial Rounded MT Bold", size: 24)!

    let scale = UIScreen.main.scale
    UIGraphicsBeginImageContextWithOptions(image.size, false, scale)

    let textFontAttributes = [
        NSAttributedStringKey.font.rawValue: textFont,
        NSAttributedStringKey.foregroundColor: textColor,
        ] as! [String : Any]
    image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))

    let rect = CGRect(origin: point, size: image.size)
    text.draw(in: rect, withAttributes: textFontAttributes )

    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

the red marque comme in ligne

text.draw(in: rect, withAttributes: textFontAttributes )

with the message: Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'


Solution

  • There are a few issues with your code. First don't use NSString, Swift native string type is String. Second you need to specify your textFontAttributes type as [NSAttributedStringKey: Any] and don't force unwrap the result. Change the return type to optional image UIImage? You can also use defer to end graphics image context when your method finishes.

    func textToImage(drawText text: String, inImage image: UIImage, atPoint point: CGPoint) -> UIImage? {
        let textColor: UIColor = .red
        let textFont = UIFont(name: "Arial Rounded MT Bold", size: 24)!
        let scale = UIScreen.main.scale
        UIGraphicsBeginImageContextWithOptions(image.size, false, scale)
        defer { UIGraphicsEndImageContext() }
        let textFontAttributes: [NSAttributedStringKey: Any] = [.font: textFont, .foregroundColor: textColor]
        image.draw(in: CGRect(origin: .zero, size: image.size))
        let rect = CGRect(origin: point, size: image.size)
        text.draw(in: rect, withAttributes: textFontAttributes)
        return UIGraphicsGetImageFromCurrentImageContext()
    }