Created
July 7, 2020 14:29
-
-
Save danielgarbien/014aa062b94819a76e4f4de40463dc1a to your computer and use it in GitHub Desktop.
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
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