Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.07 KB | None | 0 0
  1. import Foundation
  2. import UIKit
  3.  
  4. public class AvatarGenerator {
  5.  
  6. public static func avatar(for name: String, size: CGSize, backColor: UIColor? = nil) -> UIImage? {
  7. let back = backColor ?? color(for: name)
  8. let text = displayString(for: name, fontSize: size.height / 3)
  9.  
  10. UIGraphicsBeginImageContextWithOptions(size, false, 0)
  11. let context = UIGraphicsGetCurrentContext()
  12.  
  13. let rect = CGRect(origin: CGPoint.zero, size: size)
  14.  
  15.  
  16. context?.setFillColor(back.cgColor)
  17. context?.fill(rect)
  18.  
  19. let textSize = text.size()
  20.  
  21. let centerRect = CGRect(x: (size.width - textSize.width) / 2,
  22. y: (size.height - textSize.height) / 2,
  23. width: textSize.width,
  24. height: textSize.height)
  25. text.draw(in: centerRect)
  26.  
  27. let image = UIGraphicsGetImageFromCurrentImageContext()
  28.  
  29. UIGraphicsEndImageContext()
  30.  
  31. return image
  32.  
  33. }
  34.  
  35. public static func color(for name: String) -> UIColor {
  36. if name.trimmingCharacters(in: .whitespaces).utf8.count == 0 {
  37. return UIColor.slm_paleGrayColor()
  38. }
  39. // TODO: hash not guarantie that value be same after relaunch
  40. // check for string caus it seams not the case
  41. let idx = abs(name.hashValue) % saveColors.count
  42. let color = saveColors[idx]
  43.  
  44. return color
  45. }
  46.  
  47. public static let saveColors: [UIColor] = [UIColor(red:0.93, green:0.29, blue:0.16, alpha:1.00),
  48. UIColor(red:0.25, green:0.66, blue:0.01, alpha:1.00),
  49. UIColor(red:0.88, green:0.59, blue:0.01, alpha:1.00),
  50. UIColor(red:0.06, green:0.58, blue:0.93, alpha:1.00),
  51. UIColor(red:0.56, green:0.23, blue:0.97, alpha:1.00),
  52. UIColor(red:0.99, green:0.26, blue:0.50, alpha:1.00),
  53. UIColor(red:0.00, green:0.63, blue:0.77, alpha:1.00),
  54. UIColor(red:0.92, green:0.44, blue:0.01, alpha:1.00)]
  55.  
  56. static private func displayString(for name: String, fontSize: CGFloat) -> NSAttributedString {
  57. let attributes = [
  58. NSFontAttributeName : UIFont.slm_font(withSize: fontSize, weight: UIFontWeightBold),
  59. NSForegroundColorAttributeName: UIColor.white
  60. ]
  61.  
  62. var result = ""
  63.  
  64. let words = name.components(separatedBy: CharacterSet.whitespaces)
  65. for word in words.prefix(2) {
  66. if word.utf8.count == 0 {
  67. continue
  68. }
  69. let toIndex = word.index(word.startIndex, offsetBy: 1)
  70. let firstLetter = word.substring(to: toIndex).uppercased()
  71.  
  72. result += firstLetter
  73. }
  74. return NSAttributedString(string: result, attributes: attributes)
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement