ImageTextCell.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import Foundation
  2. import UIKit
  3. import DcCore
  4. import SDWebImage
  5. class ImageTextCell: BaseMessageCell {
  6. let minImageWidth: CGFloat = 125
  7. var imageHeightConstraint: NSLayoutConstraint?
  8. var imageWidthConstraint: NSLayoutConstraint?
  9. lazy var contentImageView: SDAnimatedImageView = {
  10. let imageView = SDAnimatedImageView()
  11. imageView.translatesAutoresizingMaskIntoConstraints = false
  12. imageView.setContentHuggingPriority(.defaultHigh, for: .vertical)
  13. imageView.isUserInteractionEnabled = true
  14. imageView.contentMode = .scaleAspectFill
  15. imageView.clipsToBounds = true
  16. return imageView
  17. }()
  18. /// The play button view to display on video messages.
  19. open lazy var playButtonView: PlayButtonView = {
  20. let playButtonView = PlayButtonView()
  21. playButtonView.isHidden = true
  22. translatesAutoresizingMaskIntoConstraints = false
  23. return playButtonView
  24. }()
  25. override func setupSubviews() {
  26. super.setupSubviews()
  27. contentImageView.addSubview(playButtonView)
  28. playButtonView.centerInSuperview()
  29. playButtonView.constraint(equalTo: CGSize(width: 50, height: 50))
  30. mainContentView.addArrangedSubview(contentImageView)
  31. mainContentView.addArrangedSubview(messageLabel)
  32. messageLabel.paddingLeading = 12
  33. messageLabel.paddingTrailing = 12
  34. contentImageView.constraintAlignLeadingMaxTo(mainContentView, priority: .required).isActive = true
  35. contentImageView.constraintAlignTrailingMaxTo(mainContentView, priority: .required).isActive = true
  36. let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(onImageTapped))
  37. gestureRecognizer.numberOfTapsRequired = 1
  38. contentImageView.addGestureRecognizer(gestureRecognizer)
  39. }
  40. override func update(msg: DcMsg, messageStyle: UIRectCorner, showAvatar: Bool, showName: Bool) {
  41. messageLabel.text = msg.text
  42. bottomCompactView = msg.type != DC_MSG_STICKER && msg.text?.isEmpty ?? true
  43. mainContentView.spacing = msg.text?.isEmpty ?? false ? 0 : 6
  44. topCompactView = msg.quoteText == nil ? true : false
  45. isTransparent = msg.type == DC_MSG_STICKER
  46. topLabel.isHidden = msg.type == DC_MSG_STICKER
  47. tag = msg.id
  48. if let url = msg.fileURL,
  49. (msg.type == DC_MSG_IMAGE ||
  50. msg.type == DC_MSG_GIF ||
  51. msg.type == DC_MSG_STICKER) {
  52. contentImageView.sd_setImage(with: url,
  53. placeholderImage: UIImage(color: UIColor.init(alpha: 0,
  54. red: 255,
  55. green: 255,
  56. blue: 255),
  57. size: CGSize(width: 500, height: 500)))
  58. playButtonView.isHidden = true
  59. accessibilityLabel = msg.type == DC_MSG_GIF ? String.localized("gif") : String.localized("image")
  60. setAspectRatioFor(message: msg)
  61. } else if msg.type == DC_MSG_VIDEO, let url = msg.fileURL {
  62. playButtonView.isHidden = false
  63. accessibilityLabel = String.localized("video")
  64. if let image = ThumbnailCache.shared.restoreImage(key: url.absoluteString) {
  65. contentImageView.image = image
  66. setAspectRatioFor(message: msg, with: image, isPlaceholder: false)
  67. } else {
  68. // no image in cache
  69. let placeholderImage = UIImage(color: UIColor.init(alpha: 0,
  70. red: 255,
  71. green: 255,
  72. blue: 255),
  73. size: CGSize(width: 250, height: 250))
  74. contentImageView.image = placeholderImage
  75. DispatchQueue.global(qos: .userInteractive).async {
  76. let thumbnailImage = DcUtils.generateThumbnailFromVideo(url: url)
  77. if let thumbnailImage = thumbnailImage {
  78. DispatchQueue.main.async { [weak self] in
  79. if msg.id == self?.tag {
  80. self?.contentImageView.image = thumbnailImage
  81. ThumbnailCache.shared.storeImage(image: thumbnailImage, key: url.absoluteString)
  82. }
  83. }
  84. }
  85. }
  86. setAspectRatioFor(message: msg, with: placeholderImage, isPlaceholder: true)
  87. }
  88. }
  89. super.update(msg: msg, messageStyle: messageStyle, showAvatar: showAvatar, showName: showName)
  90. }
  91. @objc func onImageTapped() {
  92. if let tableView = self.superview as? UITableView, let indexPath = tableView.indexPath(for: self) {
  93. baseDelegate?.imageTapped(indexPath: indexPath)
  94. }
  95. }
  96. private func setStickerAspectRatio(width: CGFloat, height: CGFloat) {
  97. if height == 0 || width == 0 {
  98. return
  99. }
  100. var width = width
  101. var height = height
  102. self.imageHeightConstraint?.isActive = false
  103. self.imageWidthConstraint?.isActive = false
  104. self.contentImageView.contentMode = .scaleAspectFit
  105. // check if sticker has the allowed minimal width
  106. if width < minImageWidth {
  107. height = (height / width) * minImageWidth
  108. width = minImageWidth
  109. }
  110. // check if sticker has the allowed maximal width
  111. let maxWidth = min(UIScreen.main.bounds.height, UIScreen.main.bounds.width) / 2
  112. if width > maxWidth {
  113. height = (height / width) * maxWidth
  114. width = maxWidth
  115. }
  116. self.imageWidthConstraint = self.contentImageView.widthAnchor.constraint(lessThanOrEqualToConstant: width)
  117. self.imageHeightConstraint = self.contentImageView.heightAnchor.constraint(
  118. lessThanOrEqualTo: self.contentImageView.widthAnchor,
  119. multiplier: height / width
  120. )
  121. self.imageHeightConstraint?.isActive = true
  122. self.imageWidthConstraint?.isActive = true
  123. }
  124. private func setAspectRatio(width: CGFloat, height: CGFloat) {
  125. if height == 0 || width == 0 {
  126. return
  127. }
  128. var width = width
  129. var height = height
  130. let orientation = UIApplication.shared.statusBarOrientation
  131. self.imageHeightConstraint?.isActive = false
  132. self.imageWidthConstraint?.isActive = false
  133. // check if image has the allowed minimal width
  134. if width < minImageWidth {
  135. height = (height / width) * minImageWidth
  136. width = minImageWidth
  137. }
  138. // in some cases we show images in square sizes
  139. // restrict width to half of the screen in device landscape and to 5 / 6 in portrait
  140. // it results in a good balance between message text width and image size
  141. let factor: CGFloat = orientation.isLandscape ? 1 / 2 : 5 / 6
  142. var squareSize = UIScreen.main.bounds.width * factor
  143. if height > width {
  144. // show square image for portrait images
  145. // reduce the image square size if there's no message text so that it fits best in the viewable area
  146. if squareSize > UIScreen.main.bounds.height * 5 / 8 && (messageLabel.text?.isEmpty ?? true) {
  147. squareSize = UIScreen.main.bounds.height * 5 / 8
  148. }
  149. imageHeightConstraint = self.contentImageView.heightAnchor.constraint(lessThanOrEqualToConstant: squareSize)
  150. imageWidthConstraint = self.contentImageView.widthAnchor.constraint(lessThanOrEqualToConstant: squareSize)
  151. } else {
  152. // show image in aspect ratio for landscape images
  153. if orientation.isLandscape && height > UIScreen.main.bounds.height * 5 / 8 {
  154. // shrink landscape image in landscape device orientation if image height is too big
  155. self.imageHeightConstraint = self.contentImageView.heightAnchor.constraint(lessThanOrEqualToConstant: UIScreen.main.bounds.height * 5 / 8)
  156. self.imageWidthConstraint = self.contentImageView.widthAnchor.constraint(lessThanOrEqualTo: self.contentImageView.heightAnchor,
  157. multiplier: width/height)
  158. } else {
  159. if width < squareSize {
  160. // very small width images should be forced to not be scaled down further
  161. self.imageWidthConstraint = self.contentImageView.widthAnchor.constraint(greaterThanOrEqualToConstant: width)
  162. } else {
  163. // large width images might scale down until the max allowed text width
  164. self.imageWidthConstraint = self.contentImageView.widthAnchor.constraint(lessThanOrEqualToConstant: width)
  165. }
  166. self.imageHeightConstraint = self.contentImageView.heightAnchor.constraint(
  167. lessThanOrEqualTo: self.contentImageView.widthAnchor,
  168. multiplier: height / width
  169. )
  170. }
  171. }
  172. self.imageHeightConstraint?.isActive = true
  173. self.imageWidthConstraint?.isActive = true
  174. }
  175. private func setAspectRatioFor(message: DcMsg) {
  176. var width = message.messageWidth
  177. var height = message.messageHeight
  178. if width == 0 || height == 0,
  179. let image = message.image {
  180. width = image.size.width
  181. height = image.size.height
  182. message.setLateFilingMediaSize(width: width, height: height, duration: 0)
  183. }
  184. if message.type == DC_MSG_STICKER {
  185. setStickerAspectRatio(width: width, height: height)
  186. } else {
  187. setAspectRatio(width: width, height: height)
  188. }
  189. }
  190. private func setAspectRatioFor(message: DcMsg, with image: UIImage?, isPlaceholder: Bool) {
  191. var width = message.messageWidth
  192. var height = message.messageHeight
  193. if width == 0 || height == 0,
  194. let image = image {
  195. width = image.size.width
  196. height = image.size.height
  197. if !isPlaceholder {
  198. message.setLateFilingMediaSize(width: width, height: height, duration: 0)
  199. }
  200. }
  201. setAspectRatio(width: width, height: height)
  202. }
  203. override func prepareForReuse() {
  204. super.prepareForReuse()
  205. contentImageView.image = nil
  206. contentImageView.sd_cancelCurrentImageLoad()
  207. tag = -1
  208. }
  209. }