Skip to content

Instantly share code, notes, and snippets.

@ftp27
Created September 6, 2017 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ftp27/3258e30e024c3381d1ae125c4b0ee04a to your computer and use it in GitHub Desktop.
Save ftp27/3258e30e024c3381d1ae125c4b0ee04a to your computer and use it in GitHub Desktop.
Generation UIImage with first letters of two first words
import UIKit
extension UIImage {
class func lettersPhoto(_ input: String,
size: CGSize = CGSize(width:100, height:100)) -> UIImage? {
// Color generation place
let bgColor = UIColor.black
let height = size.height/2
let letters:String = {
let maxChars = 2
let words = input.split(separator: " ")
return words[0..<min(maxChars, words.count)].reduce("") { (output, word) -> String in
guard let char = word.characters.first else { return output }
return output + String(char).uppercased()
}
}()
let attrs = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: height),
NSAttributedStringKey.foregroundColor: UIColor.white]
let stringSize = (letters as NSString).size(withAttributes: attrs)
let rect = CGRect(origin: CGPoint.zero,
size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 1)
let c = UIGraphicsGetCurrentContext()
c?.setFillColor(bgColor.cgColor)
c?.fill(rect)
letters.draw(with: CGRect(origin: CGPoint(x: (size.width - stringSize.width)/2,
y: (size.height - stringSize.height)/2),
size: stringSize),
options: .usesLineFragmentOrigin,
attributes: attrs,
context: nil)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment