Skip to content

Instantly share code, notes, and snippets.

@tad-iizuka
Created October 20, 2017 03:14
Show Gist options
  • Save tad-iizuka/58d22bed8aecfe51360b7faea4a34bcb to your computer and use it in GitHub Desktop.
Save tad-iizuka/58d22bed8aecfe51360b7faea4a34bcb to your computer and use it in GitHub Desktop.
Emoji convert to UIImage. Swift 4
func emojiToImage(text: String, size: CGFloat) -> UIImage {
let outputImageSize = CGSize.init(width: size, height: size)
let baseSize = text.boundingRect(with: CGSize(width: 2048, height: 2048),
options: .usesLineFragmentOrigin,
attributes: [.font: UIFont.systemFont(ofSize: size / 2)], context: nil).size
let fontSize = outputImageSize.width / max(baseSize.width, baseSize.height) * (outputImageSize.width / 2)
let font = UIFont.systemFont(ofSize: fontSize)
let textSize = text.boundingRect(with: CGSize(width: outputImageSize.width, height: outputImageSize.height),
options: .usesLineFragmentOrigin,
attributes: [.font: font], context: nil).size
let style = NSMutableParagraphStyle()
style.alignment = NSTextAlignment.center
style.lineBreakMode = NSLineBreakMode.byClipping
let attr : [NSAttributedStringKey : Any] = [NSAttributedStringKey.font : font,
NSAttributedStringKey.paragraphStyle: style,
NSAttributedStringKey.backgroundColor: UIColor.clear ]
UIGraphicsBeginImageContextWithOptions(outputImageSize, false, 0)
text.draw(in: CGRect(x: (size - textSize.width) / 2,
y: (size - textSize.height) / 2,
width: textSize.width,
height: textSize.height),
withAttributes: attr)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
@AshokNFN
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment