AvatarView.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. MIT License
  3. Copyright (c) 2017-2019 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. import UIKit
  22. open class AvatarView: UIImageView {
  23. // MARK: - Properties
  24. open var initials: String? {
  25. didSet {
  26. setImageFrom(initials: initials)
  27. }
  28. }
  29. open var placeholderFont: UIFont = UIFont.preferredFont(forTextStyle: .caption1) {
  30. didSet {
  31. setImageFrom(initials: initials)
  32. }
  33. }
  34. open var placeholderTextColor: UIColor = .white {
  35. didSet {
  36. setImageFrom(initials: initials)
  37. }
  38. }
  39. open var fontMinimumScaleFactor: CGFloat = 0.5
  40. open var adjustsFontSizeToFitWidth = true
  41. private var minimumFontSize: CGFloat {
  42. return placeholderFont.pointSize * fontMinimumScaleFactor
  43. }
  44. private var radius: CGFloat?
  45. // MARK: - Overridden Properties
  46. open override var frame: CGRect {
  47. didSet {
  48. setCorner(radius: self.radius)
  49. }
  50. }
  51. open override var bounds: CGRect {
  52. didSet {
  53. setCorner(radius: self.radius)
  54. }
  55. }
  56. // MARK: - Initializers
  57. public override init(frame: CGRect) {
  58. super.init(frame: frame)
  59. prepareView()
  60. }
  61. required public init?(coder aDecoder: NSCoder) {
  62. super.init(coder: aDecoder)
  63. prepareView()
  64. }
  65. convenience public init() {
  66. self.init(frame: .zero)
  67. prepareView()
  68. }
  69. private func setImageFrom(initials: String?) {
  70. guard let initials = initials else { return }
  71. image = getImageFrom(initials: initials)
  72. }
  73. private func getImageFrom(initials: String) -> UIImage {
  74. let width = frame.width
  75. let height = frame.height
  76. if width == 0 || height == 0 {return UIImage()}
  77. var font = placeholderFont
  78. _ = UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, UIScreen.main.scale)
  79. defer { UIGraphicsEndImageContext() }
  80. let context = UIGraphicsGetCurrentContext()!
  81. //// Text Drawing
  82. let textRect = calculateTextRect(outerViewWidth: width, outerViewHeight: height)
  83. let initialsText = NSAttributedString(string: initials, attributes: [.font: font])
  84. if adjustsFontSizeToFitWidth,
  85. initialsText.width(considering: textRect.height) > textRect.width {
  86. let newFontSize = calculateFontSize(text: initials, font: font, width: textRect.width, height: textRect.height)
  87. font = placeholderFont.withSize(newFontSize)
  88. }
  89. let textStyle = NSMutableParagraphStyle()
  90. textStyle.alignment = .center
  91. let textFontAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: font,
  92. NSAttributedString.Key.foregroundColor: placeholderTextColor,
  93. NSAttributedString.Key.paragraphStyle: textStyle]
  94. let textTextHeight: CGFloat = initials.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity),
  95. options: .usesLineFragmentOrigin,
  96. attributes: textFontAttributes,
  97. context: nil).height
  98. context.saveGState()
  99. context.clip(to: textRect)
  100. initials.draw(in: CGRect(textRect.minX,
  101. textRect.minY + (textRect.height - textTextHeight) / 2,
  102. textRect.width,
  103. textTextHeight),
  104. withAttributes: textFontAttributes)
  105. context.restoreGState()
  106. guard let renderedImage = UIGraphicsGetImageFromCurrentImageContext() else { assertionFailure("Could not create image from context"); return UIImage()}
  107. return renderedImage
  108. }
  109. /**
  110. Recursively find the biggest size to fit the text with a given width and height
  111. */
  112. private func calculateFontSize(text: String, font: UIFont, width: CGFloat, height: CGFloat) -> CGFloat {
  113. let attributedText = NSAttributedString(string: text, attributes: [.font: font])
  114. if attributedText.width(considering: height) > width {
  115. let newFont = font.withSize(font.pointSize - 1)
  116. if newFont.pointSize > minimumFontSize {
  117. return font.pointSize
  118. } else {
  119. return calculateFontSize(text: text, font: newFont, width: width, height: height)
  120. }
  121. }
  122. return font.pointSize
  123. }
  124. /**
  125. Calculates the inner circle's width.
  126. Note: Assumes corner radius cannot be more than width/2 (this creates circle).
  127. */
  128. private func calculateTextRect(outerViewWidth: CGFloat, outerViewHeight: CGFloat) -> CGRect {
  129. guard outerViewWidth > 0 else {
  130. return CGRect.zero
  131. }
  132. let shortEdge = min(outerViewHeight, outerViewWidth)
  133. // Converts degree to radian degree and calculate the
  134. // Assumes, it is a perfect circle based on the shorter part of ellipsoid
  135. // calculate a rectangle
  136. let w = shortEdge * sin(CGFloat(45).degreesToRadians) * 2
  137. let h = shortEdge * cos(CGFloat(45).degreesToRadians) * 2
  138. let startX = (outerViewWidth - w)/2
  139. let startY = (outerViewHeight - h)/2
  140. // In case the font exactly fits to the region, put 2 pixel both left and right
  141. return CGRect(startX+2, startY, w-4, h)
  142. }
  143. // MARK: - Internal methods
  144. internal func prepareView() {
  145. backgroundColor = .gray
  146. contentMode = .scaleAspectFill
  147. layer.masksToBounds = true
  148. clipsToBounds = true
  149. setCorner(radius: nil)
  150. }
  151. // MARK: - Open setters
  152. open func set(avatar: Avatar) {
  153. if let image = avatar.image {
  154. self.image = image
  155. } else {
  156. initials = avatar.initials
  157. }
  158. }
  159. open func setCorner(radius: CGFloat?) {
  160. guard let radius = radius else {
  161. //if corner radius not set default to Circle
  162. let cornerRadius = min(frame.width, frame.height)
  163. layer.cornerRadius = cornerRadius/2
  164. return
  165. }
  166. self.radius = radius
  167. layer.cornerRadius = radius
  168. }
  169. }
  170. fileprivate extension FloatingPoint {
  171. var degreesToRadians: Self { return self * .pi / 180 }
  172. var radiansToDegrees: Self { return self * 180 / .pi }
  173. }