iOS Swift Create Image from Text example

iOS Swift Create Image from Text example

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.navigationItem.title = "Main View"
        
        let myText = "Text to Image"
        let font = UIFont(name:"Optima-BoldItalic", size: 36.0)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = .center
        let shadow = NSShadow()
        shadow.shadowColor = UIColor.green
        shadow.shadowBlurRadius = 3
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: font ?? UIFont.systemFontSize,
            .foregroundColor: UIColor.orange,
            .shadow: shadow,
            .paragraphStyle: paragraphStyle
        ]
        
        let attributedText = NSAttributedString(string: myText, attributes: attributes)
        
        let myLabel = UILabel(frame: CGRect(x: 50, y: 50, width: 400, height: 50))
        self.view.addSubview(myLabel)
        myLabel.attributedText = attributedText
        myLabel.numberOfLines = 2
        
        let imageView = UIImageView()
        imageView.frame = CGRect(x: 50, y: 150, width: 400, height: 50)
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
        imageView.image = imageFromAttributedString(from: attributedText)
        
    }
    
    func imageFromAttributedString(from text: NSAttributedString?) -> UIImage? {
        
        //begin
        UIGraphicsBeginImageContextWithOptions(text?.size() ?? CGSize.zero, _: false, _: 0.0)
        // draw in context
        text?.draw(at: CGPoint(x: 0.0, y: 0.0))
        // transfer image
        let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()?.withRenderingMode(.alwaysOriginal)
        UIGraphicsEndImageContext()
        
        return image
    
    }
    
    
}


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.