Created
September 6, 2017 14:13
-
-
Save ftp27/3258e30e024c3381d1ae125c4b0ee04a to your computer and use it in GitHub Desktop.
Generation UIImage with first letters of two first words
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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