Created
November 5, 2019 22:19
-
-
Save DanielCardonaRojas/9ba60692a311ad0ba2ee3867d88d2eb8 to your computer and use it in GitHub Desktop.
Creates an image from initials. Use this with UIImageView
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 UIImage { | |
static func fromInitials(_ string: String, size: CGSize, backGroundColor: UIColor, textAttributes: [NSAttributedString.Key: Any]? = nil) -> UIImage? { | |
let text = string.initials | |
let scale = Float(UIScreen.main.scale) | |
UIGraphicsBeginImageContextWithOptions(size, false, CGFloat(scale)) | |
let context = UIGraphicsGetCurrentContext() | |
context?.setFillColor(backGroundColor.cgColor) | |
context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) | |
let defaultAttributes = [ | |
NSAttributedString.Key.foregroundColor: UIColor.white, | |
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0) | |
] | |
let attributes = textAttributes ?? defaultAttributes | |
let textSize = text.size(withAttributes: attributes) | |
let rect = CGRect(x: size.width/2 - textSize.width/2, | |
y: size.height/2 - textSize.height/2, | |
width: textSize.width, | |
height: textSize.height) | |
text.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