Skip to content

Instantly share code, notes, and snippets.

@danielgarbien
Created July 7, 2020 14:29
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 danielgarbien/014aa062b94819a76e4f4de40463dc1a to your computer and use it in GitHub Desktop.
Save danielgarbien/014aa062b94819a76e4f4de40463dc1a to your computer and use it in GitHub Desktop.
extension String {
func draw(fontSize: CGFloat) -> UIImage? {
draw(font: .systemFont(ofSize: fontSize))
}
func draw(font: UIFont) -> UIImage? {
draw(attributes: [.font: font], backgroundColor: .clear)
}
func draw(attributes: [NSAttributedString.Key : Any], backgroundColor: UIColor) -> UIImage? {
let size = NSString(string: self).size(withAttributes: attributes)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
backgroundColor.set()
let rect = CGRect(origin: .zero, size: size)
UIRectFill(CGRect(origin: .zero, size: size))
(self as AnyObject).draw(in: rect, withAttributes: attributes)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment