AvatarView.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2018 MessageKit
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. import Foundation
  21. open class AvatarView: UIImageView {
  22. // MARK: - Properties
  23. open var initials: String? {
  24. didSet {
  25. setImageFrom(initials: initials)
  26. }
  27. }
  28. open var placeholderFont: UIFont = UIFont.preferredFont(forTextStyle: .caption1) {
  29. didSet {
  30. setImageFrom(initials: initials)
  31. }
  32. }
  33. open var placeholderTextColor: UIColor = .white {
  34. didSet {
  35. setImageFrom(initials: initials)
  36. }
  37. }
  38. open var fontMinimumScaleFactor: CGFloat = 0.5
  39. open var adjustsFontSizeToFitWidth = true
  40. private var minimumFontSize: CGFloat {
  41. return placeholderFont.pointSize * fontMinimumScaleFactor
  42. }
  43. private var radius: CGFloat?
  44. // MARK: - Overridden Properties
  45. open override var frame: CGRect {
  46. didSet {
  47. setCorner(radius: self.radius)
  48. }
  49. }
  50. open override var bounds: CGRect {
  51. didSet {
  52. setCorner(radius: self.radius)
  53. }
  54. }
  55. // MARK: - Initializers
  56. public override init(frame: CGRect) {
  57. super.init(frame: frame)
  58. prepareView()
  59. }
  60. convenience public init() {
  61. self.init(frame: .zero)
  62. }
  63. private func setImageFrom(initials: String?) {
  64. guard let initials = initials else { return }
  65. image = getImageFrom(initials: initials)
  66. }
  67. private func getImageFrom(initials: String) -> UIImage {
  68. let width = frame.width
  69. let height = frame.height
  70. if width == 0 || height == 0 {return UIImage()}
  71. var font = placeholderFont
  72. _ = UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, UIScreen.main.scale)
  73. defer { UIGraphicsEndImageContext() }
  74. let context = UIGraphicsGetCurrentContext()!
  75. //// Text Drawing
  76. let textRect = calculateTextRect(outerViewWidth: width, outerViewHeight: height)
  77. let initialsText = NSAttributedString(string: initials, attributes: [.font: font])
  78. if adjustsFontSizeToFitWidth,
  79. initialsText.width(considering: textRect.height) > textRect.width {
  80. let newFontSize = calculateFontSize(text: initials, font: font, width: textRect.width, height: textRect.height)
  81. font = placeholderFont.withSize(newFontSize)
  82. }
  83. let textStyle = NSMutableParagraphStyle()
  84. textStyle.alignment = .center
  85. let textFontAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: placeholderTextColor, NSAttributedString.Key.paragraphStyle: textStyle]
  86. let textTextHeight: CGFloat = initials.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: textFontAttributes, context: nil).height
  87. context.saveGState()
  88. context.clip(to: textRect)
  89. initials.draw(in: CGRect(textRect.minX, textRect.minY + (textRect.height - textTextHeight) / 2, textRect.width, textTextHeight), withAttributes: textFontAttributes)
  90. context.restoreGState()
  91. guard let renderedImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Could not create image from context"); return UIImage()}
  92. return renderedImage
  93. }
  94. /**
  95. Recursively find the biggest size to fit the text with a given width and height
  96. */
  97. private func calculateFontSize(text: String, font: UIFont, width: CGFloat, height: CGFloat) -> CGFloat {
  98. let attributedText = NSAttributedString(string: text, attributes: [.font: font])
  99. if attributedText.width(considering: height) > width {
  100. let newFont = font.withSize(font.pointSize - 1)
  101. if newFont.pointSize > minimumFontSize {
  102. return font.pointSize
  103. } else {
  104. return calculateFontSize(text: text, font: newFont, width: width, height: height)
  105. }
  106. }
  107. return font.pointSize
  108. }
  109. /**
  110. Calculates the inner circle's width.
  111. Note: Assumes corner radius cannot be more than width/2 (this creates circle).
  112. */
  113. private func calculateTextRect(outerViewWidth: CGFloat, outerViewHeight: CGFloat) -> CGRect {
  114. guard outerViewWidth > 0 else {
  115. return CGRect.zero
  116. }
  117. let shortEdge = min(outerViewHeight, outerViewWidth)
  118. // Converts degree to radian degree and calculate the
  119. // Assumes, it is a perfect circle based on the shorter part of ellipsoid
  120. // calculate a rectangle
  121. let w = shortEdge * sin(CGFloat(45).degreesToRadians) * 2
  122. let h = shortEdge * cos(CGFloat(45).degreesToRadians) * 2
  123. let startX = (outerViewWidth - w)/2
  124. let startY = (outerViewHeight - h)/2
  125. // In case the font exactly fits to the region, put 2 pixel both left and right
  126. return CGRect(startX+2, startY, w-4, h)
  127. }
  128. required public init?(coder aDecoder: NSCoder) {
  129. fatalError("init(coder:) has not been implemented")
  130. }
  131. // MARK: - Internal methods
  132. internal func prepareView() {
  133. backgroundColor = .gray
  134. contentMode = .scaleAspectFill
  135. layer.masksToBounds = true
  136. clipsToBounds = true
  137. setCorner(radius: nil)
  138. }
  139. // MARK: - Open setters
  140. open func set(avatar: Avatar) {
  141. if let image = avatar.image {
  142. self.image = image
  143. } else {
  144. initials = avatar.initials
  145. }
  146. }
  147. open func setCorner(radius: CGFloat?) {
  148. guard let radius = radius else {
  149. //if corner radius not set default to Circle
  150. let cornerRadius = min(frame.width, frame.height)
  151. layer.cornerRadius = cornerRadius/2
  152. return
  153. }
  154. self.radius = radius
  155. layer.cornerRadius = radius
  156. }
  157. }
  158. fileprivate extension FloatingPoint {
  159. var degreesToRadians: Self { return self * .pi / 180 }
  160. var radiansToDegrees: Self { return self * 180 / .pi }
  161. }