Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Foundation
- import UIKit
- public class AvatarGenerator {
- public static func avatar(for name: String, size: CGSize, backColor: UIColor? = nil) -> UIImage? {
- let back = backColor ?? color(for: name)
- let text = displayString(for: name, fontSize: size.height / 3)
- UIGraphicsBeginImageContextWithOptions(size, false, 0)
- let context = UIGraphicsGetCurrentContext()
- let rect = CGRect(origin: CGPoint.zero, size: size)
- context?.setFillColor(back.cgColor)
- context?.fill(rect)
- let textSize = text.size()
- let centerRect = CGRect(x: (size.width - textSize.width) / 2,
- y: (size.height - textSize.height) / 2,
- width: textSize.width,
- height: textSize.height)
- text.draw(in: centerRect)
- let image = UIGraphicsGetImageFromCurrentImageContext()
- UIGraphicsEndImageContext()
- return image
- }
- public static func color(for name: String) -> UIColor {
- if name.trimmingCharacters(in: .whitespaces).utf8.count == 0 {
- return UIColor.slm_paleGrayColor()
- }
- // TODO: hash not guarantie that value be same after relaunch
- // check for string caus it seams not the case
- let idx = abs(name.hashValue) % saveColors.count
- let color = saveColors[idx]
- return color
- }
- public static let saveColors: [UIColor] = [UIColor(red:0.93, green:0.29, blue:0.16, alpha:1.00),
- UIColor(red:0.25, green:0.66, blue:0.01, alpha:1.00),
- UIColor(red:0.88, green:0.59, blue:0.01, alpha:1.00),
- UIColor(red:0.06, green:0.58, blue:0.93, alpha:1.00),
- UIColor(red:0.56, green:0.23, blue:0.97, alpha:1.00),
- UIColor(red:0.99, green:0.26, blue:0.50, alpha:1.00),
- UIColor(red:0.00, green:0.63, blue:0.77, alpha:1.00),
- UIColor(red:0.92, green:0.44, blue:0.01, alpha:1.00)]
- static private func displayString(for name: String, fontSize: CGFloat) -> NSAttributedString {
- let attributes = [
- NSFontAttributeName : UIFont.slm_font(withSize: fontSize, weight: UIFontWeightBold),
- NSForegroundColorAttributeName: UIColor.white
- ]
- var result = ""
- let words = name.components(separatedBy: CharacterSet.whitespaces)
- for word in words.prefix(2) {
- if word.utf8.count == 0 {
- continue
- }
- let toIndex = word.index(word.startIndex, offsetBy: 1)
- let firstLetter = word.substring(to: toIndex).uppercased()
- result += firstLetter
- }
- return NSAttributedString(string: result, attributes: attributes)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement