Swift 3 Generate UIImage of Letters from String

Generate an Image of Letters from a String in Swift 3 in a few minutes!

 

Hello...

Starting up the old blog again

 

 

https://github.com/mattmega4/ImageFromTextTutorial

Ever wondered how your favorite apps are able to generate letters in absence of a picture on say a profile picture.  Do these developers sit at their desks creating actual images all the possible 1-2 letter combinations? Probably not! I'm embarrassed to say that I started to do this until I learned this cool code.

Think about all the combinations you would have to do. A-Z for just the one letter initials. Then A+A-Z, B+A-Z..... too many. In the following short tutorial you will learn how to take text, say Harry Potter, and generate an actual image of HP. 

 

Now before we continue there are always multiple ways to accomplish something. Some make more sense than other and some less. However, I believe in being aware of the other options so you at least have it in your bag of tricks. So again, this is not the only way to do this, and it might not even be the "best way"

 

I personally like seeing the final result of a tutorial before I dive in, so without further blabbering from me, here is the final result.

https://github.com/mattmega4/ImageFromTextTutorial

 

FinalPreviewOne

Before

Typing in "Harry James Potter"

FinalPreviewTwo

After

The First and Last initial "HP" is generated as an Image

I am going to assume you have a general understanding of iOS Development and Swift programming. In an attempt to make my tutorials shorter I am going to be creating less screen shots than my previous blog.

 

Ready?

 

Create a new project and call it whatever you want.

I like to clean my project up before I start to work. I do this by creating "Groups"

I create: Model, View, Controller, and Additional Files.

I also create an Extensions Group but that does not apply for this simple tutorial.

Put: Assets, AppDelegate, LaunchScreen, and Info.plist into the Additional Files.

Put ViewController into Controller

Put Main.Storyboard into View

Click once on the Model Folder, and Control + Click and select "New File"

 

newFile

Make sure iOS is Highlighted

Cocoa Touch Class then Next

newFileTwo

Subclass NSObject

Name it: LetterImageGenerator

Ok, pretty straight forward. Select Cocoa Touch Class and make sure iOS is selected and hit Next. Start typing NSObject into the Subclass of (it should autocomplete) then name the Class LetterImageGenerator (doesn't really matter what you name it as long as it makes sense, always try to name things according to what it does)

 

Great. Now here comes a bit of code

 

That is 99% of all you need to do to make this work. The other 1% is just tiny things that you can do in your sleep. This will save you from creating however many combinations of A-Z one letter, an A-Z two letter combos.

I understand that may be hard to see on the screen so here is the code..

class LetterImageGenerator: NSObject {
  class func imageWith(name: String?) -> UIImage? {
    let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    let nameLabel = UILabel(frame: frame)
    nameLabel.textAlignment = .center
    nameLabel.backgroundColor = .lightGray
    nameLabel.textColor = .white
    nameLabel.font = UIFont.boldSystemFont(ofSize: 20)
    var initials = ""
    if let initialsArray = name?.components(separatedBy: " ") {
      if let firstWord = initialsArray.first {
        if let firstLetter = firstWord.characters.first {
          initials += String(firstLetter).capitalized
        }
      }
      if initialsArray.count > 1, let lastWord = initialsArray.last {
        if let lastLetter = lastWord.characters.first {
          initials += String(lastLetter).capitalized
        }
      }
    } else {
      return nil
    }
    nameLabel.text = initials
    UIGraphicsBeginImageContext(frame.size)
    if let currentContext = UIGraphicsGetCurrentContext() {
      nameLabel.layer.render(in: currentContext)
      let nameImage = UIGraphicsGetImageFromCurrentImageContext()
      return nameImage
    }
    return nil
  }
}

 

THATS IT!!

Now, if you look though the code you will notice I have firstWord and lastWord in there. So, If I put Harry Potter I would get HP, if I put Harry James Potter I would still get HP. I made this with the intent of working with a First, Middle, and Last name and knowing I only wanted to show the First & Last Initials.

However, I have a separate app where I am not dealign with peoples names and I only wanted the first letter of the first word. The point is this is just a starting point. You can and should customize this to work for your apps needs.

Screen Shot 2017-07-30 at 12.52.47 AM.png

Basic View

Simple 

This is how it should look!

This is how it should look!

Harry Potter

I typed in Harry Potter and got HP

Thats it. Now just to clarify...This code as is will work for the first letter of the first and last words...so it will work if you have 1 word or 10...

It is up to you to make the code so you could perhaps only be able to enter 3 words...or have 3 textfields and then combine the text from each textfield...or whatever you want.

this is just a starting point.

See the full project on my Github

https://github.com/mattmega4/ImageFromTextTutorial

Make sure to Star & Follow if you found this Tutorial helpful!