ZLPhotoPreviewCell.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. //
  2. // ZLPhotoPreviewCell.swift
  3. // ZLPhotoBrowser
  4. //
  5. // Created by long on 2020/8/21.
  6. //
  7. // Copyright (c) 2020 Long Zhang <495181165@qq.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import UIKit
  27. import Photos
  28. import PhotosUI
  29. class ZLPreviewBaseCell: UICollectionViewCell {
  30. var singleTapBlock: ( () -> Void )?
  31. var currentImage: UIImage? {
  32. return nil
  33. }
  34. override init(frame: CGRect) {
  35. super.init(frame: frame)
  36. NotificationCenter.default.addObserver(self, selector: #selector(previewVCScroll), name: ZLPhotoPreviewController.previewVCScrollNotification, object: nil)
  37. }
  38. required init?(coder: NSCoder) {
  39. fatalError("init(coder:) has not been implemented")
  40. }
  41. @objc func previewVCScroll() {
  42. }
  43. func resetSubViewStatusWhenCellEndDisplay() {
  44. }
  45. func resizeImageView(imageView: UIImageView, asset: PHAsset) {
  46. let size = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
  47. var frame: CGRect = .zero
  48. let viewW = self.bounds.width
  49. let viewH = self.bounds.height
  50. var width = viewW
  51. // video和livephoto没必要处理长图和宽图
  52. if UIApplication.shared.statusBarOrientation.isLandscape {
  53. let height = viewH
  54. frame.size.height = height
  55. let imageWHRatio = size.width / size.height
  56. let viewWHRatio = viewW / viewH
  57. if imageWHRatio > viewWHRatio {
  58. frame.size.width = floor(height * imageWHRatio)
  59. if frame.size.width > viewW {
  60. frame.size.width = viewW
  61. frame.size.height = viewW / imageWHRatio
  62. }
  63. } else {
  64. width = floor(height * imageWHRatio)
  65. if width < 1 || width.isNaN {
  66. width = viewW
  67. }
  68. frame.size.width = width
  69. }
  70. } else {
  71. frame.size.width = width
  72. let imageHWRatio = size.height / size.width
  73. let viewHWRatio = viewH / viewW
  74. if imageHWRatio > viewHWRatio {
  75. frame.size.height = floor(width * imageHWRatio)
  76. } else {
  77. var height = floor(width * imageHWRatio)
  78. if height < 1 || height.isNaN {
  79. height = viewH
  80. }
  81. frame.size.height = height
  82. }
  83. }
  84. imageView.frame = frame
  85. if UIApplication.shared.statusBarOrientation.isLandscape {
  86. if frame.height < viewH {
  87. imageView.center = CGPoint(x: viewW / 2, y: viewH / 2)
  88. } else {
  89. imageView.frame = CGRect(origin: CGPoint(x: (viewW-frame.width)/2, y: 0), size: frame.size)
  90. }
  91. } else {
  92. if frame.width < viewW || frame.height < viewH {
  93. imageView.center = CGPoint(x: viewW / 2, y: viewH / 2)
  94. }
  95. }
  96. }
  97. func animateImageFrame(convertTo view: UIView) -> CGRect {
  98. return .zero
  99. }
  100. }
  101. // MARK: local and net image preview cell
  102. class ZLLocalImagePreviewCell: ZLPreviewBaseCell {
  103. override var currentImage: UIImage? {
  104. return self.preview.image
  105. }
  106. var preview: ZLPreviewView!
  107. var image: UIImage? = nil {
  108. didSet {
  109. self.preview.imageView.image = image
  110. self.preview.resetSubViewSize()
  111. }
  112. }
  113. var longPressBlock: ( () -> Void )?
  114. deinit {
  115. zl_debugPrint("ZLLocalImagePreviewCell deinit")
  116. }
  117. override init(frame: CGRect) {
  118. super.init(frame: frame)
  119. self.setupUI()
  120. }
  121. required init?(coder: NSCoder) {
  122. fatalError("init(coder:) has not been implemented")
  123. }
  124. override func layoutSubviews() {
  125. super.layoutSubviews()
  126. self.preview.frame = self.bounds
  127. }
  128. private func setupUI() {
  129. self.preview = ZLPreviewView()
  130. self.preview.singleTapBlock = { [weak self] in
  131. self?.singleTapBlock?()
  132. }
  133. self.contentView.addSubview(self.preview)
  134. let longGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:)))
  135. longGes.minimumPressDuration = 0.5
  136. self.addGestureRecognizer(longGes)
  137. }
  138. override func resetSubViewStatusWhenCellEndDisplay() {
  139. self.preview.scrollView.zoomScale = 1
  140. }
  141. @objc func longPressAction(_ ges: UILongPressGestureRecognizer) {
  142. guard let _ = self.currentImage else {
  143. return
  144. }
  145. if ges.state == .began {
  146. self.longPressBlock?()
  147. }
  148. }
  149. }
  150. // MARK: net image preview cell
  151. class ZLNetImagePreviewCell: ZLLocalImagePreviewCell {
  152. var progressView: ZLProgressView!
  153. var progress: CGFloat = 0 {
  154. didSet {
  155. progressView.progress = progress
  156. progressView.isHidden = progress >= 1
  157. }
  158. }
  159. override init(frame: CGRect) {
  160. super.init(frame: frame)
  161. self.progressView = ZLProgressView()
  162. self.progressView.isHidden = true
  163. self.contentView.addSubview(self.progressView)
  164. }
  165. required init?(coder: NSCoder) {
  166. fatalError("init(coder:) has not been implemented")
  167. }
  168. override func layoutSubviews() {
  169. super.layoutSubviews()
  170. self.bringSubviewToFront(self.progressView)
  171. self.progressView.frame = CGRect(x: self.bounds.width / 2 - 20, y: self.bounds.height / 2 - 20, width: 40, height: 40)
  172. }
  173. override func resetSubViewStatusWhenCellEndDisplay() {
  174. self.progressView.isHidden = true
  175. self.preview.scrollView.zoomScale = 1
  176. }
  177. }
  178. // MARK: static image preview cell
  179. class ZLPhotoPreviewCell: ZLPreviewBaseCell {
  180. override var currentImage: UIImage? {
  181. return self.preview.image
  182. }
  183. var preview: ZLPreviewView!
  184. var model: ZLPhotoModel! {
  185. didSet {
  186. self.preview.model = self.model
  187. }
  188. }
  189. deinit {
  190. zl_debugPrint("ZLPhotoPreviewCell deinit")
  191. }
  192. override init(frame: CGRect) {
  193. super.init(frame: frame)
  194. self.setupUI()
  195. }
  196. required init?(coder: NSCoder) {
  197. fatalError("init(coder:) has not been implemented")
  198. }
  199. override func layoutSubviews() {
  200. super.layoutSubviews()
  201. self.preview.frame = self.bounds
  202. }
  203. private func setupUI() {
  204. self.preview = ZLPreviewView()
  205. self.preview.singleTapBlock = { [weak self] in
  206. self?.singleTapBlock?()
  207. }
  208. self.contentView.addSubview(self.preview)
  209. }
  210. override func resetSubViewStatusWhenCellEndDisplay() {
  211. self.preview.scrollView.zoomScale = 1
  212. }
  213. override func animateImageFrame(convertTo view: UIView) -> CGRect {
  214. let r1 = self.preview.scrollView.convert(self.preview.containerView.frame, to: self)
  215. return self.convert(r1, to: view)
  216. }
  217. }
  218. // MARK: gif preview cell
  219. class ZLGifPreviewCell: ZLPreviewBaseCell {
  220. override var currentImage: UIImage? {
  221. return self.preview.image
  222. }
  223. var preview: ZLPreviewView!
  224. var model: ZLPhotoModel! {
  225. didSet {
  226. self.preview.model = self.model
  227. }
  228. }
  229. deinit {
  230. zl_debugPrint("ZLGifPreviewCell deinit")
  231. }
  232. override init(frame: CGRect) {
  233. super.init(frame: frame)
  234. self.setupUI()
  235. }
  236. required init?(coder: NSCoder) {
  237. fatalError("init(coder:) has not been implemented")
  238. }
  239. override func layoutSubviews() {
  240. super.layoutSubviews()
  241. self.preview.frame = self.bounds
  242. }
  243. private func setupUI() {
  244. self.preview = ZLPreviewView()
  245. self.preview.singleTapBlock = { [weak self] in
  246. self?.singleTapBlock?()
  247. }
  248. self.contentView.addSubview(self.preview)
  249. }
  250. override func previewVCScroll() {
  251. self.preview.pauseGif()
  252. }
  253. func resumeGif() {
  254. self.preview.resumeGif()
  255. }
  256. func pauseGif() {
  257. self.preview.pauseGif()
  258. }
  259. /// gif图加载会导致主线程卡顿一下,所以放在willdisplay时候加载
  260. func loadGifWhenCellDisplaying() {
  261. self.preview.loadGifData()
  262. }
  263. override func resetSubViewStatusWhenCellEndDisplay() {
  264. self.preview.scrollView.zoomScale = 1
  265. }
  266. override func animateImageFrame(convertTo view: UIView) -> CGRect {
  267. let r1 = self.preview.scrollView.convert(self.preview.containerView.frame, to: self)
  268. return self.convert(r1, to: view)
  269. }
  270. }
  271. // MARK: live photo preview cell
  272. class ZLLivePhotoPreviewCell: ZLPreviewBaseCell {
  273. override var currentImage: UIImage? {
  274. return self.imageView.image
  275. }
  276. var livePhotoView: PHLivePhotoView!
  277. var imageView: UIImageView!
  278. var imageRequestID: PHImageRequestID = PHInvalidImageRequestID
  279. var livePhotoRequestID: PHImageRequestID = PHInvalidImageRequestID
  280. var onFetchingLivePhoto = false
  281. var fetchLivePhotoDone = false
  282. var model: ZLPhotoModel! {
  283. didSet {
  284. self.loadNormalImage()
  285. }
  286. }
  287. deinit {
  288. zl_debugPrint("ZLLivePhotoPewviewCell deinit")
  289. }
  290. override init(frame: CGRect) {
  291. super.init(frame: frame)
  292. self.setupUI()
  293. }
  294. required init?(coder: NSCoder) {
  295. fatalError("init(coder:) has not been implemented")
  296. }
  297. override func layoutSubviews() {
  298. super.layoutSubviews()
  299. self.livePhotoView.frame = self.bounds
  300. self.resizeImageView(imageView: self.imageView, asset: self.model.asset)
  301. }
  302. private func setupUI() {
  303. self.livePhotoView = PHLivePhotoView()
  304. self.livePhotoView.contentMode = .scaleAspectFit
  305. self.contentView.addSubview(self.livePhotoView)
  306. self.imageView = UIImageView()
  307. self.imageView.contentMode = .scaleAspectFit
  308. self.contentView.addSubview(self.imageView)
  309. }
  310. override func previewVCScroll() {
  311. self.livePhotoView.stopPlayback()
  312. }
  313. func loadNormalImage() {
  314. if self.imageRequestID > PHInvalidImageRequestID {
  315. PHImageManager.default().cancelImageRequest(self.imageRequestID)
  316. }
  317. if self.livePhotoRequestID > PHInvalidImageRequestID {
  318. PHImageManager.default().cancelImageRequest(self.livePhotoRequestID)
  319. }
  320. self.onFetchingLivePhoto = false
  321. self.imageView.isHidden = false
  322. // livephoto 加载个较小的预览图即可
  323. var size = self.model.previewSize
  324. size.width /= 4
  325. size.height /= 4
  326. self.resizeImageView(imageView: self.imageView, asset: self.model.asset)
  327. self.imageRequestID = ZLPhotoManager.fetchImage(for: self.model.asset, size: size, completion: { [weak self] (image, isDegread) in
  328. self?.imageView.image = image
  329. })
  330. }
  331. func loadLivePhotoData() {
  332. guard !self.onFetchingLivePhoto else {
  333. if self.fetchLivePhotoDone {
  334. self.startPlayLivePhoto()
  335. }
  336. return
  337. }
  338. self.onFetchingLivePhoto = true
  339. self.fetchLivePhotoDone = false
  340. self.livePhotoRequestID = ZLPhotoManager.fetchLivePhoto(for: self.model.asset, completion: { (livePhoto, info, isDegraded) in
  341. if !isDegraded {
  342. self.fetchLivePhotoDone = true
  343. self.livePhotoView.livePhoto = livePhoto
  344. self.startPlayLivePhoto()
  345. }
  346. })
  347. }
  348. func startPlayLivePhoto() {
  349. self.imageView.isHidden = true
  350. self.livePhotoView.startPlayback(with: .full)
  351. }
  352. override func animateImageFrame(convertTo view: UIView) -> CGRect {
  353. return self.convert(self.imageView.frame, to: view)
  354. }
  355. }
  356. // MARK: video preview cell
  357. class ZLVideoPreviewCell: ZLPreviewBaseCell {
  358. override var currentImage: UIImage? {
  359. return self.imageView.image
  360. }
  361. var player: AVPlayer?
  362. var playerLayer: AVPlayerLayer?
  363. var progressView: ZLProgressView!
  364. var imageView: UIImageView!
  365. var playBtn: UIButton!
  366. var syncErrorLabel: UILabel!
  367. var imageRequestID: PHImageRequestID = PHInvalidImageRequestID
  368. var videoRequestID: PHImageRequestID = PHInvalidImageRequestID
  369. var onFetchingVideo = false
  370. var fetchVideoDone = false
  371. var isPlaying: Bool {
  372. if self.player != nil, self.player?.rate != 0 {
  373. return true
  374. }
  375. return false
  376. }
  377. var model: ZLPhotoModel! {
  378. didSet {
  379. self.configureCell()
  380. }
  381. }
  382. deinit {
  383. zl_debugPrint("ZLVideoPreviewCell deinit")
  384. }
  385. override init(frame: CGRect) {
  386. super.init(frame: frame)
  387. self.setupUI()
  388. }
  389. required init?(coder: NSCoder) {
  390. fatalError("init(coder:) has not been implemented")
  391. }
  392. override func layoutSubviews() {
  393. super.layoutSubviews()
  394. self.playerLayer?.frame = self.bounds
  395. self.resizeImageView(imageView: self.imageView, asset: self.model.asset)
  396. let insets = deviceSafeAreaInsets()
  397. self.playBtn.frame = CGRect(x: 0, y: insets.top, width: self.bounds.width, height: self.bounds.height - insets.top - insets.bottom)
  398. self.syncErrorLabel.frame = CGRect(x: 10, y: insets.top + 60, width: self.bounds.width - 20, height: 35)
  399. self.progressView.frame = CGRect(x: self.bounds.width / 2 - 30, y: self.bounds.height / 2 - 30, width: 60, height: 60)
  400. }
  401. private func setupUI() {
  402. self.imageView = UIImageView()
  403. self.imageView.clipsToBounds = true
  404. self.imageView.contentMode = .scaleAspectFill
  405. self.contentView.addSubview(self.imageView)
  406. let attStr = NSMutableAttributedString()
  407. let attach = NSTextAttachment()
  408. attach.image = getImage("zl_videoLoadFailed")
  409. attach.bounds = CGRect(x: 0, y: -10, width: 30, height: 30)
  410. attStr.append(NSAttributedString(attachment: attach))
  411. let errorText = NSAttributedString(string: localLanguageTextValue(.iCloudVideoLoadFaild), attributes: [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: getFont(12)])
  412. attStr.append(errorText)
  413. self.syncErrorLabel = UILabel()
  414. self.syncErrorLabel.attributedText = attStr
  415. self.contentView.addSubview(self.syncErrorLabel)
  416. self.progressView = ZLProgressView()
  417. self.contentView.addSubview(self.progressView)
  418. self.playBtn = UIButton(type: .custom)
  419. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  420. self.playBtn.addTarget(self, action: #selector(playBtnClick), for: .touchUpInside)
  421. self.contentView.addSubview(self.playBtn)
  422. NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
  423. }
  424. func configureCell() {
  425. self.imageView.image = nil
  426. self.imageView.isHidden = false
  427. self.syncErrorLabel.isHidden = true
  428. self.playBtn.isEnabled = false
  429. self.player = nil
  430. self.playerLayer?.removeFromSuperlayer()
  431. self.playerLayer = nil
  432. if self.imageRequestID > PHInvalidImageRequestID {
  433. PHImageManager.default().cancelImageRequest(self.imageRequestID)
  434. }
  435. if self.videoRequestID > PHInvalidImageRequestID {
  436. PHImageManager.default().cancelImageRequest(self.videoRequestID)
  437. }
  438. // 视频预览图尺寸
  439. var size = self.model.previewSize
  440. size.width /= 2
  441. size.height /= 2
  442. self.resizeImageView(imageView: self.imageView, asset: self.model.asset)
  443. self.imageRequestID = ZLPhotoManager.fetchImage(for: self.model.asset, size: size, completion: { (image, isDegraded) in
  444. self.imageView.image = image
  445. })
  446. self.videoRequestID = ZLPhotoManager.fetchVideo(for: self.model.asset, progress: { [weak self] (progress, _, _, _) in
  447. self?.progressView.progress = progress
  448. zl_debugPrint("video progress \(progress)")
  449. if progress >= 1 {
  450. zl_debugPrint("video load finished")
  451. self?.progressView.isHidden = true
  452. } else {
  453. self?.progressView.isHidden = false
  454. }
  455. }, completion: { [weak self] (item, info, isDegraded) in
  456. let error = info?[PHImageErrorKey] as? Error
  457. let isFetchError = ZLPhotoManager.isFetchImageError(error)
  458. if isFetchError {
  459. self?.syncErrorLabel.isHidden = false
  460. self?.playBtn.setImage(nil, for: .normal)
  461. }
  462. if !isDegraded, item != nil {
  463. self?.fetchVideoDone = true
  464. self?.configurePlayerLayer(item!)
  465. }
  466. })
  467. }
  468. func configurePlayerLayer(_ item: AVPlayerItem) {
  469. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  470. self.playBtn.isEnabled = true
  471. self.player = AVPlayer(playerItem: item)
  472. self.playerLayer = AVPlayerLayer(player: self.player)
  473. self.playerLayer?.frame = self.bounds
  474. self.layer.insertSublayer(self.playerLayer!, at: 0)
  475. NotificationCenter.default.addObserver(self, selector: #selector(playFinish), name: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
  476. }
  477. @objc func playBtnClick() {
  478. let currentTime = self.player?.currentItem?.currentTime()
  479. let duration = self.player?.currentItem?.duration
  480. if self.player?.rate == 0 {
  481. if currentTime?.value == duration?.value {
  482. self.player?.currentItem?.seek(to: CMTimeMake(value: 0, timescale: 1))
  483. }
  484. self.imageView.isHidden = true
  485. self.player?.play()
  486. self.playBtn.setImage(nil, for: .normal)
  487. self.singleTapBlock?()
  488. } else {
  489. self.pausePlayer(seekToZero: false)
  490. }
  491. }
  492. @objc func playFinish() {
  493. self.pausePlayer(seekToZero: true)
  494. }
  495. @objc func appWillResignActive() {
  496. if self.player != nil, self.player?.rate != 0 {
  497. self.pausePlayer(seekToZero: false)
  498. }
  499. }
  500. override func previewVCScroll() {
  501. if self.player != nil, self.player?.rate != 0 {
  502. self.pausePlayer(seekToZero: false)
  503. }
  504. }
  505. override func resetSubViewStatusWhenCellEndDisplay() {
  506. self.imageView.isHidden = false
  507. self.player?.currentItem?.seek(to: CMTimeMake(value: 0, timescale: 1))
  508. }
  509. func pausePlayer(seekToZero: Bool) {
  510. self.player?.pause()
  511. if seekToZero {
  512. self.player?.seek(to: .zero)
  513. }
  514. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  515. self.singleTapBlock?()
  516. }
  517. func pauseWhileTransition() {
  518. self.player?.pause()
  519. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  520. }
  521. override func animateImageFrame(convertTo view: UIView) -> CGRect {
  522. return self.convert(self.imageView.frame, to: view)
  523. }
  524. }
  525. // MARK: net video preview cell
  526. class ZLNetVideoPreviewCell: ZLPreviewBaseCell {
  527. var player: AVPlayer?
  528. var playerLayer: AVPlayerLayer?
  529. var playBtn: UIButton!
  530. var isPlaying: Bool {
  531. if self.player != nil, self.player?.rate != 0 {
  532. return true
  533. }
  534. return false
  535. }
  536. var videoUrl: URL! {
  537. didSet {
  538. self.configureCell()
  539. }
  540. }
  541. deinit {
  542. zl_debugPrint("v deinit")
  543. }
  544. override init(frame: CGRect) {
  545. super.init(frame: frame)
  546. self.setupUI()
  547. }
  548. required init?(coder: NSCoder) {
  549. fatalError("init(coder:) has not been implemented")
  550. }
  551. override func layoutSubviews() {
  552. super.layoutSubviews()
  553. self.playerLayer?.frame = self.bounds
  554. let insets = deviceSafeAreaInsets()
  555. self.playBtn.frame = CGRect(x: 0, y: insets.top, width: self.bounds.width, height: self.bounds.height - insets.top - insets.bottom)
  556. }
  557. private func setupUI() {
  558. self.playBtn = UIButton(type: .custom)
  559. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  560. self.playBtn.addTarget(self, action: #selector(playBtnClick), for: .touchUpInside)
  561. self.contentView.addSubview(self.playBtn)
  562. NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
  563. }
  564. func configureCell() {
  565. self.player = nil
  566. self.playerLayer?.removeFromSuperlayer()
  567. self.playerLayer = nil
  568. self.player = AVPlayer(playerItem: AVPlayerItem(url: self.videoUrl))
  569. self.playerLayer = AVPlayerLayer(player: self.player)
  570. self.playerLayer?.frame = self.bounds
  571. self.layer.insertSublayer(self.playerLayer!, at: 0)
  572. NotificationCenter.default.addObserver(self, selector: #selector(playFinish), name: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem)
  573. }
  574. @objc func playBtnClick() {
  575. let currentTime = self.player?.currentItem?.currentTime()
  576. let duration = self.player?.currentItem?.duration
  577. if self.player?.rate == 0 {
  578. if currentTime?.value == duration?.value {
  579. self.player?.currentItem?.seek(to: CMTimeMake(value: 0, timescale: 1))
  580. }
  581. self.player?.play()
  582. self.playBtn.setImage(nil, for: .normal)
  583. self.singleTapBlock?()
  584. } else {
  585. self.pausePlayer(seekToZero: false)
  586. }
  587. }
  588. @objc func playFinish() {
  589. self.pausePlayer(seekToZero: true)
  590. }
  591. @objc func appWillResignActive() {
  592. if self.player != nil, self.player?.rate != 0 {
  593. self.pausePlayer(seekToZero: false)
  594. }
  595. }
  596. override func previewVCScroll() {
  597. if self.player != nil, self.player?.rate != 0 {
  598. self.pausePlayer(seekToZero: false)
  599. }
  600. }
  601. override func resetSubViewStatusWhenCellEndDisplay() {
  602. self.player?.currentItem?.seek(to: CMTimeMake(value: 0, timescale: 1))
  603. }
  604. func pausePlayer(seekToZero: Bool) {
  605. self.player?.pause()
  606. if seekToZero {
  607. self.player?.seek(to: .zero)
  608. }
  609. self.playBtn.setImage(getImage("zl_playVideo"), for: .normal)
  610. self.singleTapBlock?()
  611. }
  612. }
  613. // MARK: class ZLPreviewView
  614. class ZLPreviewView: UIView {
  615. static let defaultMaxZoomScale: CGFloat = 3
  616. var scrollView: UIScrollView!
  617. var containerView: UIView!
  618. var imageView: UIImageView!
  619. var image: UIImage? {
  620. self.imageView.image
  621. }
  622. var progressView: ZLProgressView!
  623. var singleTapBlock: ( () -> Void )?
  624. var doubleTapBlock: ( () -> Void )?
  625. var imageRequestID: PHImageRequestID = PHInvalidImageRequestID
  626. var gifImageRequestID: PHImageRequestID = PHInvalidImageRequestID
  627. var imageIdentifier: String = ""
  628. var onFetchingGif = false
  629. var fetchGifDone = false
  630. var model: ZLPhotoModel! {
  631. didSet {
  632. self.configureView()
  633. }
  634. }
  635. override init(frame: CGRect) {
  636. super.init(frame: frame)
  637. self.setupUI()
  638. }
  639. required init?(coder: NSCoder) {
  640. fatalError("init(coder:) has not been implemented")
  641. }
  642. override func layoutSubviews() {
  643. super.layoutSubviews()
  644. self.scrollView.frame = self.bounds
  645. self.progressView.frame = CGRect(x: self.bounds.width / 2 - 20, y: self.bounds.height / 2 - 20, width: 40, height: 40)
  646. self.scrollView.zoomScale = 1
  647. self.resetSubViewSize()
  648. }
  649. func setupUI() {
  650. self.scrollView = UIScrollView()
  651. self.scrollView.maximumZoomScale = ZLPreviewView.defaultMaxZoomScale
  652. self.scrollView.minimumZoomScale = 1
  653. self.scrollView.isMultipleTouchEnabled = true
  654. self.scrollView.delegate = self
  655. self.scrollView.showsHorizontalScrollIndicator = false
  656. self.scrollView.showsVerticalScrollIndicator = false
  657. self.scrollView.delaysContentTouches = false
  658. self.addSubview(self.scrollView)
  659. self.containerView = UIView()
  660. self.scrollView.addSubview(self.containerView)
  661. self.imageView = UIImageView()
  662. self.imageView.contentMode = .scaleAspectFill
  663. self.imageView.clipsToBounds = true
  664. self.containerView.addSubview(self.imageView)
  665. self.progressView = ZLProgressView()
  666. self.addSubview(self.progressView)
  667. let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapAction(_:)))
  668. self.addGestureRecognizer(singleTap)
  669. let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction(_:)))
  670. doubleTap.numberOfTapsRequired = 2
  671. self.addGestureRecognizer(doubleTap)
  672. singleTap.require(toFail: doubleTap)
  673. }
  674. @objc func singleTapAction(_ tap: UITapGestureRecognizer) {
  675. self.singleTapBlock?()
  676. }
  677. @objc func doubleTapAction(_ tap: UITapGestureRecognizer) {
  678. let scale: CGFloat = self.scrollView.zoomScale != self.scrollView.maximumZoomScale ? self.scrollView.maximumZoomScale : 1
  679. let tapPoint = tap.location(in: self)
  680. var rect = CGRect.zero
  681. rect.size.width = self.scrollView.frame.width / scale
  682. rect.size.height = self.scrollView.frame.height / scale
  683. rect.origin.x = tapPoint.x - (rect.size.width / 2)
  684. rect.origin.y = tapPoint.y - (rect.size.height / 2)
  685. self.scrollView.zoom(to: rect, animated: true)
  686. }
  687. func configureView() {
  688. if self.imageRequestID > PHInvalidImageRequestID {
  689. PHImageManager.default().cancelImageRequest(self.imageRequestID)
  690. }
  691. if self.gifImageRequestID > PHInvalidImageRequestID {
  692. PHImageManager.default().cancelImageRequest(self.gifImageRequestID)
  693. }
  694. self.scrollView.zoomScale = 1
  695. self.imageIdentifier = self.model.ident
  696. if ZLPhotoConfiguration.default().allowSelectGif, self.model.type == .gif {
  697. self.loadGifFirstFrame()
  698. } else {
  699. self.loadPhoto()
  700. }
  701. }
  702. func requestPhotoSize(gif: Bool) -> CGSize {
  703. // gif 情况下优先加载一个小的缩略图
  704. var size = self.model.previewSize
  705. if gif {
  706. size.width /= 2
  707. size.height /= 2
  708. }
  709. return size
  710. }
  711. func loadPhoto() {
  712. if let editImage = self.model.editImage {
  713. self.imageView.image = editImage
  714. self.resetSubViewSize()
  715. } else {
  716. self.imageRequestID = ZLPhotoManager.fetchImage(for: self.model.asset, size: self.requestPhotoSize(gif: false), progress: { [weak self] (progress, _, _, _) in
  717. self?.progressView.progress = progress
  718. if progress >= 1 {
  719. self?.progressView.isHidden = true
  720. } else {
  721. self?.progressView.isHidden = false
  722. }
  723. }, completion: { [weak self] (image, isDegraded) in
  724. guard self?.imageIdentifier == self?.model.ident else {
  725. return
  726. }
  727. self?.imageView.image = image
  728. self?.resetSubViewSize()
  729. if !isDegraded {
  730. self?.progressView.isHidden = true
  731. self?.imageRequestID = PHInvalidImageRequestID
  732. }
  733. })
  734. }
  735. }
  736. func loadGifFirstFrame() {
  737. self.onFetchingGif = false
  738. self.fetchGifDone = false
  739. self.imageRequestID = ZLPhotoManager.fetchImage(for: self.model.asset, size: self.requestPhotoSize(gif: true), completion: { [weak self] (image, isDegraded) in
  740. guard self?.imageIdentifier == self?.model.ident else {
  741. return
  742. }
  743. if self?.fetchGifDone == false {
  744. self?.imageView.image = image
  745. self?.resetSubViewSize()
  746. }
  747. })
  748. }
  749. func loadGifData() {
  750. guard !self.onFetchingGif else {
  751. if self.fetchGifDone {
  752. self.resumeGif()
  753. }
  754. return
  755. }
  756. self.onFetchingGif = true
  757. self.fetchGifDone = false
  758. self.imageView.layer.speed = 1
  759. self.imageView.layer.timeOffset = 0
  760. self.imageView.layer.beginTime = 0
  761. self.gifImageRequestID = ZLPhotoManager.fetchOriginalImageData(for: self.model.asset, progress: { [weak self] (progress, _, _, _) in
  762. self?.progressView.progress = progress
  763. if progress >= 1 {
  764. self?.progressView.isHidden = true
  765. } else {
  766. self?.progressView.isHidden = false
  767. }
  768. }, completion: { [weak self] (data, _, isDegraded) in
  769. guard self?.imageIdentifier == self?.model.ident else {
  770. return
  771. }
  772. if !isDegraded {
  773. self?.fetchGifDone = true
  774. self?.imageView.image = UIImage.zl_animateGifImage(data: data)
  775. self?.resetSubViewSize()
  776. }
  777. })
  778. }
  779. func resetSubViewSize() {
  780. let size: CGSize
  781. if let _ = self.model {
  782. if let ei = self.model.editImage {
  783. size = ei.size
  784. } else {
  785. size = CGSize(width: self.model.asset.pixelWidth, height: self.model.asset.pixelHeight)
  786. }
  787. } else {
  788. size = self.imageView.image?.size ?? self.bounds.size
  789. }
  790. var frame: CGRect = .zero
  791. let viewW = self.bounds.width
  792. let viewH = self.bounds.height
  793. var width = viewW
  794. if UIApplication.shared.statusBarOrientation.isLandscape {
  795. let height = viewH
  796. frame.size.height = height
  797. let imageWHRatio = size.width / size.height
  798. let viewWHRatio = viewW / viewH
  799. if imageWHRatio > viewWHRatio {
  800. frame.size.width = floor(height * imageWHRatio)
  801. if frame.size.width > viewW {
  802. // 宽图
  803. frame.size.width = viewW
  804. frame.size.height = viewW / imageWHRatio
  805. }
  806. } else {
  807. width = floor(height * imageWHRatio)
  808. if width < 1 || width.isNaN {
  809. width = viewW
  810. }
  811. frame.size.width = width
  812. }
  813. } else {
  814. frame.size.width = width
  815. let imageHWRatio = size.height / size.width
  816. let viewHWRatio = viewH / viewW
  817. if imageHWRatio > viewHWRatio {
  818. // 长图
  819. frame.size.width = min(size.width, viewW)
  820. frame.size.height = floor(frame.size.width * imageHWRatio)
  821. } else {
  822. var height = floor(frame.size.width * imageHWRatio)
  823. if height < 1 || height.isNaN {
  824. height = viewH
  825. }
  826. frame.size.height = height
  827. }
  828. }
  829. // 优化 scroll view zoom scale
  830. if frame.width < frame.height {
  831. self.scrollView.maximumZoomScale = max(ZLPreviewView.defaultMaxZoomScale, viewW / frame.width)
  832. } else {
  833. self.scrollView.maximumZoomScale = max(ZLPreviewView.defaultMaxZoomScale, viewH / frame.height)
  834. }
  835. self.containerView.frame = frame
  836. var contenSize: CGSize = .zero
  837. if UIApplication.shared.statusBarOrientation.isLandscape {
  838. contenSize = CGSize(width: width, height: max(viewH, frame.height))
  839. if frame.height < viewH {
  840. self.containerView.center = CGPoint(x: viewW / 2, y: viewH / 2)
  841. } else {
  842. self.containerView.frame = CGRect(origin: CGPoint(x: (viewW-frame.width)/2, y: 0), size: frame.size)
  843. }
  844. } else {
  845. contenSize = frame.size
  846. if frame.width < viewW || frame.height < viewH {
  847. self.containerView.center = CGPoint(x: viewW / 2, y: viewH / 2)
  848. }
  849. }
  850. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  851. self.scrollView.contentSize = contenSize
  852. self.imageView.frame = self.containerView.bounds
  853. self.scrollView.contentOffset = .zero
  854. }
  855. }
  856. func resumeGif() {
  857. guard let m = self.model else { return }
  858. guard ZLPhotoConfiguration.default().allowSelectGif && m.type == .gif else { return }
  859. guard self.imageView.layer.speed != 1 else { return }
  860. let pauseTime = self.imageView.layer.timeOffset
  861. self.imageView.layer.speed = 1
  862. self.imageView.layer.timeOffset = 0
  863. self.imageView.layer.beginTime = 0
  864. let timeSincePause = self.imageView.layer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime
  865. self.imageView.layer.beginTime = timeSincePause
  866. }
  867. func pauseGif() {
  868. guard let m = self.model else { return }
  869. guard ZLPhotoConfiguration.default().allowSelectGif && m.type == .gif else { return }
  870. guard self.imageView.layer.speed != 0 else { return }
  871. let pauseTime = self.imageView.layer.convertTime(CACurrentMediaTime(), from: nil)
  872. self.imageView.layer.speed = 0
  873. self.imageView.layer.timeOffset = pauseTime
  874. }
  875. }
  876. extension ZLPreviewView: UIScrollViewDelegate {
  877. func viewForZooming(in scrollView: UIScrollView) -> UIView? {
  878. return self.containerView
  879. }
  880. func scrollViewDidZoom(_ scrollView: UIScrollView) {
  881. let offsetX = (scrollView.frame.width > scrollView.contentSize.width) ? (scrollView.frame.width - scrollView.contentSize.width) * 0.5 : 0
  882. let offsetY = (scrollView.frame.height > scrollView.contentSize.height) ? (scrollView.frame.height - scrollView.contentSize.height) * 0.5 : 0
  883. self.containerView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
  884. }
  885. func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  886. self.resumeGif()
  887. }
  888. }