Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate an UIImage from custom text in Swift

I am trying to generate an UIImage from custom text in Swift3.

Using iOS Controls, It's possible to create an UIImage, below is the code:

class func imageWithText(txtField: UITextField) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(txtField.bounds.size, false, 0.0)
        txtField.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }

Note: I know it's also possible to add some text to an image, but I don't want to do like this.

Can someone help me to resolve this? Thank you!

like image 919
user2786 Avatar asked Jun 29 '18 10:06

user2786


People also ask

How do you declare UIImage in Objective C?

For example: UIImage *img = [[UIImage alloc] init]; [img setImage:[UIImage imageNamed:@"anyImageName"]]; My UIImage object is declared in . h file and allocated in init method, I need to set image in viewDidLoad method.

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

What is use of UIImageView?

Whenever you want an image in a view controller, you use a UIImageView. A UIImageView contains a UIImage, which is the raw bitmap, and allows you to configure how you want to scale or crop the image.

What is UIImage in Swift?

An object that manages image data in your app.


1 Answers

Here is a String extension that can be used as shown below to create UIImage instances from a String instance, without the need for UI controls like UITextField or UILabel as requested in the original question:

var image: UIImage? =
    "Test".image(withAttributes: [
        .foregroundColor: UIColor.red,
        .font: UIFont.systemFont(ofSize: 30.0),
    ], size: CGSize(width: 300.0, height: 80.0))

// Or
image = "Test".image(withAttributes: [.font: UIFont.systemFont(ofSize: 80.0)])

// Or
image = "Test".image(size: CGSize(width: 300.0, height: 80.0))

// Or even just
image = "Test".image()

Playground Sampler

Below are two possible implementations for achieving the desired effect demonstrated above:

UIGraphicsImageRenderer Method (more performant and recommended implementation by Apple)

extension String {
    
    /// Generates a `UIImage` instance from this string using a specified
    /// attributes and size.
    ///
    /// - Parameters:
    ///     - attributes: to draw this string with. Default is `nil`.
    ///     - size: of the image to return.
    /// - Returns: a `UIImage` instance from this string using a specified
    /// attributes and size, or `nil` if the operation fails.
    func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
        let size = size ?? (self as NSString).size(withAttributes: attributes)
        return UIGraphicsImageRenderer(size: size).image { _ in
            (self as NSString).draw(in: CGRect(origin: .zero, size: size),
                                    withAttributes: attributes)
        }
    }
    
}

UIGraphicsImageContext Method (old-school; included for thoroughness)

extension String {
    
    /// Generates a `UIImage` instance from this string using a specified
    /// attributes and size.
    ///
    /// - Parameters:
    ///     - attributes: to draw this string with. Default is `nil`.
    ///     - size: of the image to return.
    /// - Returns: a `UIImage` instance from this string using a specified
    /// attributes and size, or `nil` if the operation fails.
    func image(withAttributes attributes: [NSAttributedString.Key: Any]? = nil, size: CGSize? = nil) -> UIImage? {
        let size = size ?? (self as NSString).size(withAttributes: attributes)
        UIGraphicsBeginImageContext(size)
        (self as NSString).draw(in: CGRect(origin: .zero, size: size), 
                                withAttributes: attributes)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
}
like image 190
NoodleOfDeath Avatar answered Oct 21 '22 14:10

NoodleOfDeath