BFVideoThumbProgressView.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. //
  2. // BFVideoThumbProgressView.swift
  3. // BFRecordScreenKit
  4. //
  5. // Created by 胡志强 on 2021/12/3.
  6. //
  7. import AVFoundation
  8. import BFCommonKit
  9. import BFUIKit
  10. import Foundation
  11. import SnapKit
  12. import UIKit
  13. class BFVideoThumbProgressView: UIView {
  14. var recordItem: BFRecordItemModel? {
  15. didSet {
  16. // 指针回归
  17. BFLog(1, message: "new recorditem")
  18. progress = 0
  19. if recordItem?.mediaType == .VIDEO {
  20. dealWithVideoThumb()
  21. } else if recordItem?.mediaType == .IMAGE {
  22. dealWithImageThumb()
  23. }
  24. }
  25. }
  26. var dragScrollProgressHandle: ((Bool, Float) -> Void)?
  27. var dragEndHandle: ((Float) -> Void)?
  28. var dragStartHandle: (() -> Void)?
  29. var isDrag = false
  30. let thumbImageWidth: CGFloat = 70.0
  31. let fetchThumbStrategy: BFVideoThumbProgressStrategyProtocol = BFVideoThumbProgressStrategy()
  32. var progress: Double = 0 { // 进度,秒为单位
  33. didSet {
  34. updateProgress(progress: progress)
  35. }
  36. }
  37. var thumbImgs = [UIImage]()
  38. lazy var progressView: BFAutolayoutScrollView = {
  39. let sv = BFAutolayoutScrollView()
  40. sv.bounces = false
  41. // sv.backgroundColor = .clear
  42. // sv.backgroundColor = UIColor.hexColor(hexadecimal: "#888888",alpha:0.3)
  43. sv.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
  44. sv.decelerationRate = .fast
  45. sv.showsHorizontalScrollIndicator = false
  46. sv.delegate = self
  47. return sv
  48. }()
  49. lazy var progessIndicateBackV: UIView = {
  50. let vv = UIView()
  51. return vv
  52. }()
  53. // MARK: - 生命周期
  54. override init(frame: CGRect) {
  55. super.init(frame: frame)
  56. addSubview(progressView)
  57. let line = UIView()
  58. line.backgroundColor = .white
  59. line.layer.borderColor = UIColor.black.cgColor
  60. line.layer.borderWidth = 0.3
  61. line.layer.cornerRadius = 1.5
  62. addSubview(line)
  63. line.snp.makeConstraints { make in
  64. make.width.equalTo(3)
  65. make.center.height.equalToSuperview()
  66. }
  67. progressView.contentView.addSubview(progessIndicateBackV)
  68. progessIndicateBackV.snp.makeConstraints { make in
  69. make.left.equalTo(width * 0.5)
  70. make.right.equalTo(width * -0.5)
  71. make.bottom.equalToSuperview()
  72. make.height.equalTo(6)
  73. make.width.equalTo(1).priority(.high)
  74. }
  75. }
  76. required init?(coder _: NSCoder) {
  77. fatalError("init(coder:) has not been implemented")
  78. }
  79. override func layoutSubviews() {
  80. super.layoutSubviews()
  81. progressView.snp.makeConstraints { make in
  82. make.edges.equalToSuperview()
  83. }
  84. }
  85. /// 处理视频缩略图
  86. func dealWithVideoThumb() {
  87. guard let videoAsset = recordItem?.videoAsset else {
  88. // 可能icloud资源没回来,清空原有内容
  89. addThumbImages(images: [UIImage]())
  90. return
  91. }
  92. addThumbImages(images: recordItem!.thumbImgs)
  93. if recordItem!.thumbImgs.count > 0 {
  94. // 代表已经获取过了,不用在重新去获得
  95. progessIndicateBackV.snp.remakeConstraints { make in
  96. make.left.equalTo(width * 0.5)
  97. make.right.equalTo(width * -0.5)
  98. make.bottom.equalToSuperview()
  99. make.height.equalTo(6)
  100. make.width.equalTo(CGFloat(recordItem!.thumbImgs.count) * thumbImageWidth).priority(.high)
  101. }
  102. return
  103. }
  104. let date = Date()
  105. let dur = videoAsset.duration.seconds
  106. if dur > 0 {
  107. let count = fetchThumbStrategy.frameNumberOfVideo(assetDuration: dur)
  108. progessIndicateBackV.snp.remakeConstraints { make in
  109. make.left.equalTo(width * 0.5)
  110. make.right.equalTo(width * -0.5)
  111. make.bottom.equalToSuperview()
  112. make.height.equalTo(6)
  113. make.width.equalTo(CGFloat(count) * thumbImageWidth).priority(.high)
  114. }
  115. recordItem!.splitVideoFileUrlFps(frames: count, firstImagesCount: Int(ceil(width / 2.0 / thumbImageWidth))) { [weak self, weak recordItem] hadGetAll, images in
  116. guard let sself = self, let sitem = recordItem else {
  117. return
  118. }
  119. BFLog(1, message: "获取缩略图:\(hadGetAll), \(Date().timeIntervalSince(date)), \(sitem.localPath ?? "aa")")
  120. sitem.thumbImgs.removeAll()
  121. sitem.thumbImgs.append(contentsOf: images)
  122. // 不足数则补充足够帧数
  123. while hadGetAll, sitem.thumbImgs.count < count, images.count > 0 {
  124. sitem.thumbImgs.append(images.last!)
  125. }
  126. if sitem.localPath == sself.recordItem!.localPath {
  127. sself.addThumbImages(images: sitem.thumbImgs)
  128. } else {
  129. BFLog(1, message: "thumbImgs.count:\(sitem.thumbImgs.count)")
  130. }
  131. }
  132. }
  133. }
  134. /// 处理图片缩略图
  135. func dealWithImageThumb() {
  136. guard let image = recordItem?.coverImg else {
  137. addThumbImages(images: [UIImage]())
  138. return
  139. }
  140. addThumbImages(images: Array(repeating: image, count: 30))
  141. }
  142. /// 添加缩略图
  143. /// - Parameter images: <#images description#>
  144. func addThumbImages(images: [UIImage]) {
  145. DispatchQueue.main.async { [weak self] in
  146. self?.progressView.contentView.subviews.forEach { subview in
  147. if subview is UIImageView {
  148. subview.removeFromSuperview()
  149. }
  150. }
  151. if images.count > 0 {
  152. // self?.thumbImgs = images
  153. if let sself = self {
  154. var lastImg = UIImageView()
  155. for (i, img) in images.enumerated() {
  156. let iv = UIImageView(image: img)
  157. iv.contentMode = .scaleAspectFill
  158. iv.clipsToBounds = true
  159. sself.progressView.contentView.insertSubview(iv, belowSubview: sself.progessIndicateBackV)
  160. iv.snp.makeConstraints { make in
  161. make.left.equalTo(CGFloat(i) * CGFloat(sself.thumbImageWidth) + sself.width * 0.5)
  162. make.top.bottom.equalToSuperview()
  163. make.height.equalTo(50)
  164. make.width.equalTo(sself.thumbImageWidth)
  165. }
  166. lastImg = iv
  167. }
  168. if sself.recordItem?.mediaType == .IMAGE {
  169. // 图片需要动态修改宽度
  170. lastImg.snp.makeConstraints { make in
  171. make.right.equalTo(sself.width * -0.5)
  172. make.height.equalTo(50)
  173. make.width.equalTo(sself.thumbImageWidth)
  174. }
  175. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { [weak self] in
  176. lastImg.snp.updateConstraints { make in
  177. make.width.equalTo(self?.thumbImageWidth ?? 70)
  178. }
  179. }
  180. }
  181. }
  182. }
  183. }
  184. }
  185. func appendThumb(progress: Double = 0) {
  186. let count: Int = Int(progress / 2)
  187. BFLog(message: "需要的图片个数:progress=\(progress),count=\(count)")
  188. if recordItem?.mediaType == .IMAGE, (thumbImgs.count - 5) < count {
  189. guard let image = recordItem?.coverImg else {
  190. return
  191. }
  192. var lastiv = UIImageView()
  193. let lastIndex = thumbImgs.count - 1
  194. for i in lastIndex ... lastIndex + 10 {
  195. let iv = UIImageView(image: image)
  196. iv.contentMode = .scaleAspectFill
  197. iv.clipsToBounds = true
  198. progressView.contentView.addSubview(iv)
  199. iv.snp.makeConstraints { make in
  200. make.left.equalTo(CGFloat(i) * CGFloat(thumbImageWidth) + width * 0.5)
  201. make.top.bottom.equalToSuperview()
  202. make.height.equalTo(50)
  203. make.width.equalTo(thumbImageWidth)
  204. }
  205. lastiv = iv
  206. thumbImgs.append(image)
  207. }
  208. lastiv.snp.makeConstraints { make in
  209. make.right.equalTo(width * -0.5)
  210. make.height.equalTo(50)
  211. make.width.equalTo(thumbImageWidth)
  212. }
  213. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { [weak self] in
  214. lastiv.snp.updateConstraints { make in
  215. make.width.equalTo(self?.thumbImageWidth ?? 70)
  216. }
  217. }
  218. }
  219. }
  220. /// 更新进度
  221. /// - Parameter progress: <#progress description#>
  222. func updateProgress(progress: Double = 0) {
  223. if progressView.contentSize.width <= 0 {
  224. return
  225. }
  226. if recordItem?.mediaType == .VIDEO {
  227. if let second = recordItem?.materialDuraion, second > 0 {
  228. let w = progressView.contentSize.width - width
  229. BFLog(message: "录音进度--指示器:progress=\(progress),duration=\(second),w=\(w),perW=\(Double(w) / second),totalW:\(progress * Double(w) / second)")
  230. progressView.contentOffset = CGPoint(x: progress * Double(w) / second, y: 0)
  231. }
  232. } else if recordItem?.mediaType == .IMAGE {
  233. // if (recordItem?.materialDuraion ?? 0) > progress {
  234. BFLog(message: "updateProgress:\(progress)")
  235. progressView.contentOffset = CGPoint(x: progress * thumbImageWidth / 2.0, y: 0)
  236. appendThumb(progress: progress)
  237. // }
  238. }
  239. }
  240. }
  241. extension BFVideoThumbProgressView: UIScrollViewDelegate {
  242. func scrollViewDidScroll(_ scrollView: UIScrollView) {
  243. let totalW = recordItem?.mediaType == .VIDEO ? (scrollView.contentSize.width - width) : (CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0)
  244. if recordItem?.mediaType == .VIDEO {
  245. if isDrag {
  246. dragScrollProgressHandle?(false, totalW > 0 ? Float(scrollView.contentOffset.x / totalW) : 0)
  247. }
  248. } else if recordItem?.mediaType == .IMAGE {
  249. if isDrag {
  250. if scrollView.contentOffset.x > CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0 {
  251. scrollView.contentOffset = CGPoint(x: CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0, y: 0)
  252. }
  253. dragScrollProgressHandle?(false, totalW > 0 ? Float(scrollView.contentOffset.x / totalW) : 0)
  254. }
  255. }
  256. }
  257. func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  258. isDrag = true
  259. let totalW = recordItem?.mediaType == .VIDEO ? (scrollView.contentSize.width - width) : (CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0)
  260. dragStartHandle?()
  261. dragScrollProgressHandle?(true, totalW > 0 ? Float(scrollView.contentOffset.x / totalW) : 0)
  262. }
  263. func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  264. if !decelerate {
  265. let totalW = recordItem?.mediaType == .VIDEO ? (scrollView.contentSize.width - width) : (CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0)
  266. isDrag = false
  267. dragEndHandle?(totalW > 0 ? Float(scrollView.contentOffset.x / totalW) : 0)
  268. }
  269. }
  270. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  271. let totalW = recordItem?.mediaType == .VIDEO ? (scrollView.contentSize.width - width) : (CGFloat(recordItem?.materialDuraion ?? 0) * thumbImageWidth / 2.0)
  272. isDrag = false
  273. dragEndHandle?(totalW > 0 ? Float(scrollView.contentOffset.x / totalW) : 0)
  274. }
  275. }