Convert String to Image using UIGraphics


Hi Friends,

Its Simple to convert a String to image by using UIGraphics. Here I have shared a code. This is a extension function of String. It will return a Image.

// MARK: - String Extension functions.
extension String {
    
    /// Convert String to Image
    ///
    /// - Returns: image.
    func image() -> UIImage? {
        // Size of Image
        let size = CGSize(width: 100, height: 100)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set() //clear.set()
        
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 90)])
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

– How to make an iOS App
ktrkathir