Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created November 5, 2019 22:19
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 DanielCardonaRojas/9ba60692a311ad0ba2ee3867d88d2eb8 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/9ba60692a311ad0ba2ee3867d88d2eb8 to your computer and use it in GitHub Desktop.
Creates an image from initials. Use this with UIImageView
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