Created
January 11, 2018 10:13
-
-
Save SergeyPetrachkov/4bbe6150b037fac066ba38778d9cd006 to your computer and use it in GitHub Desktop.
Create image with specified color and text inside like Telegram's conversation default avatar
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 roundedTextAvatar(text: String?, | |
color: UIColor, | |
circular: Bool, | |
textAttributes: [NSAttributedStringKey: Any]?, | |
size: CGSize) -> UIImage? { | |
let scale = Float(UIScreen.main.scale) | |
UIGraphicsBeginImageContextWithOptions(size, false, CGFloat(scale)) | |
let context = UIGraphicsGetCurrentContext() | |
if circular { | |
let path = CGPath(ellipseIn: CGRect(origin: CGPoint.zero, size: size), transform: nil) | |
context?.addPath(path) | |
context?.clip() | |
} | |
// Fill | |
context?.setFillColor(color.cgColor) | |
context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) | |
// Text | |
if let text = text { | |
let attributes = textAttributes ?? [NSAttributedStringKey.foregroundColor: UIColor.white, | |
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 15.0)] | |
let textSize = text.size(withAttributes: attributes) | |
let bounds = CGRect(origin: CGPoint.zero, size: size) | |
let rect = CGRect(x: bounds.size.width/2 - textSize.width/2, | |
y: bounds.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