ZLImagePreviewController.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. //
  2. // ZLImagePreviewController.swift
  3. // ZLPhotoBrowser
  4. //
  5. // Created by long on 2020/10/22.
  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. @objc public enum ZLURLType: Int {
  29. case image
  30. case video
  31. }
  32. public class ZLImagePreviewController: UIViewController {
  33. static let colItemSpacing: CGFloat = 40
  34. static let selPhotoPreviewH: CGFloat = 100
  35. let datas: [Any]
  36. var selectStatus: [Bool]
  37. let urlType: ( (URL) -> ZLURLType )?
  38. let urlImageLoader: ( (URL, UIImageView, @escaping ( (CGFloat) -> Void ), @escaping ( () -> Void )) -> Void )?
  39. let showSelectBtn: Bool
  40. let showBottomView: Bool
  41. var currentIndex: Int
  42. var indexBeforOrientationChanged: Int
  43. var collectionView: UICollectionView!
  44. var navView: UIView!
  45. var navBlurView: UIVisualEffectView?
  46. var backBtn: UIButton!
  47. var indexLabel: UILabel!
  48. var selectBtn: UIButton!
  49. var bottomView: UIView!
  50. var bottomBlurView: UIVisualEffectView?
  51. var doneBtn: UIButton!
  52. var isFirstAppear = true
  53. var hideNavView = false
  54. @objc public var doneBlock: ( ([Any]) -> Void )?
  55. var orientation: UIInterfaceOrientation = .unknown
  56. public override var prefersStatusBarHidden: Bool {
  57. return !ZLPhotoConfiguration.default().showStatusBarInPreviewInterface
  58. }
  59. public override var preferredStatusBarStyle: UIStatusBarStyle {
  60. return ZLPhotoConfiguration.default().statusBarStyle
  61. }
  62. /// - Parameters:
  63. /// - datas: Must be one of PHAsset, UIImage and URL, will filter ohers in init function.
  64. /// - showBottomView: If showSelectBtn is true, showBottomView is always true.
  65. /// - index: Index for first display.
  66. /// - urlType: Tell me the url is image or video.
  67. /// - urlImageLoader: Called when cell will display, cell will layout after callback when image load finish. The first block is progress callback, second is load finish callback.
  68. @objc public init(datas: [Any], index: Int = 0, showSelectBtn: Bool = true, showBottomView: Bool = true, urlType: ( (URL) -> ZLURLType )? = nil, urlImageLoader: ( (URL, UIImageView, @escaping ( (CGFloat) -> Void ), @escaping ( () -> Void )) -> Void )? = nil) {
  69. let filterDatas = datas.filter { (obj) -> Bool in
  70. return obj is PHAsset || obj is UIImage || obj is URL
  71. }
  72. self.datas = filterDatas
  73. self.selectStatus = Array(repeating: true, count: filterDatas.count)
  74. self.currentIndex = index >= filterDatas.count ? 0 : index
  75. self.indexBeforOrientationChanged = self.currentIndex
  76. self.showSelectBtn = showSelectBtn
  77. self.showBottomView = showSelectBtn ? true : showBottomView
  78. self.urlType = urlType
  79. self.urlImageLoader = urlImageLoader
  80. super.init(nibName: nil, bundle: nil)
  81. }
  82. required init?(coder: NSCoder) {
  83. fatalError("init(coder:) has not been implemented")
  84. }
  85. public override func viewDidLoad() {
  86. super.viewDidLoad()
  87. self.setupUI()
  88. self.resetSubViewStatus()
  89. }
  90. public override func viewWillAppear(_ animated: Bool) {
  91. super.viewWillAppear(animated)
  92. self.navigationController?.navigationBar.isHidden = true
  93. }
  94. public override func viewDidAppear(_ animated: Bool) {
  95. super.viewDidAppear(animated)
  96. guard self.isFirstAppear else { return }
  97. self.isFirstAppear = false
  98. self.reloadCurrentCell()
  99. }
  100. public override func viewDidLayoutSubviews() {
  101. super.viewDidLayoutSubviews()
  102. var insets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
  103. if #available(iOS 11.0, *) {
  104. insets = self.view.safeAreaInsets
  105. }
  106. insets.top = max(20, insets.top)
  107. self.collectionView.frame = CGRect(x: -ZLPhotoPreviewController.colItemSpacing / 2, y: 0, width: self.view.frame.width + ZLPhotoPreviewController.colItemSpacing, height: self.view.frame.height)
  108. let navH = insets.top + 44
  109. self.navView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: navH)
  110. self.navBlurView?.frame = self.navView.bounds
  111. self.backBtn.frame = CGRect(x: insets.left, y: insets.top, width: 60, height: 44)
  112. self.indexLabel.frame = CGRect(x: (self.view.frame.width - 80)/2, y: insets.top, width: 80, height: 44)
  113. self.selectBtn.frame = CGRect(x: self.view.frame.width - 40 - insets.right, y: insets.top + (44 - 25) / 2, width: 25, height: 25)
  114. let bottomViewH = ZLLayout.bottomToolViewH
  115. self.bottomView.frame = CGRect(x: 0, y: self.view.frame.height-insets.bottom-bottomViewH, width: self.view.frame.width, height: bottomViewH+insets.bottom)
  116. self.bottomBlurView?.frame = self.bottomView.bounds
  117. self.resetBottomViewFrame()
  118. let ori = UIApplication.shared.statusBarOrientation
  119. if ori != self.orientation {
  120. self.orientation = ori
  121. self.collectionView.setContentOffset(CGPoint(x: (self.view.frame.width + ZLPhotoPreviewController.colItemSpacing) * CGFloat(self.indexBeforOrientationChanged), y: 0), animated: false)
  122. self.collectionView.performBatchUpdates({
  123. self.collectionView.setContentOffset(CGPoint(x: (self.view.frame.width + ZLPhotoPreviewController.colItemSpacing) * CGFloat(self.indexBeforOrientationChanged), y: 0), animated: false)
  124. })
  125. }
  126. }
  127. func reloadCurrentCell() {
  128. guard let cell = self.collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0)) else {
  129. return
  130. }
  131. if let cell = cell as? ZLGifPreviewCell {
  132. cell.loadGifWhenCellDisplaying()
  133. } else if let cell = cell as? ZLLivePhotoPreviewCell {
  134. cell.loadLivePhotoData()
  135. }
  136. }
  137. private func setupUI() {
  138. self.view.backgroundColor = .black
  139. self.automaticallyAdjustsScrollViewInsets = false
  140. // nav view
  141. self.navView = UIView()
  142. self.navView.backgroundColor = .navBarColor
  143. self.view.addSubview(self.navView)
  144. if let effect = ZLPhotoConfiguration.default().navViewBlurEffect {
  145. self.navBlurView = UIVisualEffectView(effect: effect)
  146. self.navView.addSubview(self.navBlurView!)
  147. }
  148. self.backBtn = UIButton(type: .custom)
  149. self.backBtn.setImage(getImage("zl_navBack"), for: .normal)
  150. self.backBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
  151. self.backBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
  152. self.navView.addSubview(self.backBtn)
  153. self.indexLabel = UILabel()
  154. self.indexLabel.textColor = ZLPhotoConfiguration.default().themeColorDeploy.navTitleColor
  155. self.indexLabel.font = ZLLayout.navTitleFont
  156. self.indexLabel.textAlignment = .center
  157. self.navView.addSubview(self.indexLabel)
  158. self.selectBtn = UIButton(type: .custom)
  159. self.selectBtn.setImage(getImage("zl_btn_circle"), for: .normal)
  160. self.selectBtn.setImage(getImage("zl_btn_selected"), for: .selected)
  161. self.selectBtn.zl_enlargeValidTouchArea(inset: 10)
  162. self.selectBtn.addTarget(self, action: #selector(selectBtnClick), for: .touchUpInside)
  163. self.navView.addSubview(self.selectBtn)
  164. // collection view
  165. let layout = UICollectionViewFlowLayout()
  166. layout.scrollDirection = .horizontal
  167. self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
  168. self.collectionView.backgroundColor = .clear
  169. self.collectionView.dataSource = self
  170. self.collectionView.delegate = self
  171. self.collectionView.isPagingEnabled = true
  172. self.collectionView.showsHorizontalScrollIndicator = false
  173. self.view.addSubview(self.collectionView)
  174. ZLPhotoPreviewCell.zl_register(self.collectionView)
  175. ZLGifPreviewCell.zl_register(self.collectionView)
  176. ZLLivePhotoPreviewCell.zl_register(self.collectionView)
  177. ZLVideoPreviewCell.zl_register(self.collectionView)
  178. ZLLocalImagePreviewCell.zl_register(self.collectionView)
  179. ZLNetImagePreviewCell.zl_register(self.collectionView)
  180. ZLNetVideoPreviewCell.zl_register(self.collectionView)
  181. // bottom view
  182. self.bottomView = UIView()
  183. self.bottomView.backgroundColor = .bottomToolViewBgColor
  184. self.view.addSubview(self.bottomView)
  185. if let effect = ZLPhotoConfiguration.default().bottomToolViewBlurEffect {
  186. self.bottomBlurView = UIVisualEffectView(effect: effect)
  187. self.bottomView.addSubview(self.bottomBlurView!)
  188. }
  189. func createBtn(_ title: String, _ action: Selector) -> UIButton {
  190. let btn = UIButton(type: .custom)
  191. btn.titleLabel?.font = ZLLayout.bottomToolTitleFont
  192. btn.setTitle(title, for: .normal)
  193. btn.setTitleColor(.bottomToolViewBtnNormalTitleColor, for: .normal)
  194. btn.setTitleColor(.bottomToolViewBtnDisableTitleColor, for: .disabled)
  195. btn.addTarget(self, action: action, for: .touchUpInside)
  196. return btn
  197. }
  198. self.doneBtn = createBtn(localLanguageTextValue(.done), #selector(doneBtnClick))
  199. self.doneBtn.backgroundColor = .bottomToolViewBtnNormalBgColor
  200. self.doneBtn.layer.masksToBounds = true
  201. self.doneBtn.layer.cornerRadius = ZLLayout.bottomToolBtnCornerRadius
  202. self.bottomView.addSubview(self.doneBtn)
  203. self.view.bringSubviewToFront(self.navView)
  204. }
  205. func resetSubViewStatus() {
  206. self.indexLabel.text = String(self.currentIndex + 1) + " / " + String(self.datas.count)
  207. if self.showSelectBtn {
  208. self.selectBtn.isSelected = self.selectStatus[self.currentIndex]
  209. } else {
  210. self.selectBtn.isHidden = true
  211. }
  212. self.resetBottomViewFrame()
  213. }
  214. func resetBottomViewFrame() {
  215. if self.showBottomView {
  216. let btnY: CGFloat = ZLLayout.bottomToolBtnY
  217. var doneTitle = localLanguageTextValue(.done)
  218. let selCount = self.selectStatus.filter{ $0 }.count
  219. if self.showSelectBtn, selCount > 0 {
  220. doneTitle += "(" + String(selCount) + ")"
  221. }
  222. let doneBtnW = doneTitle.boundingRect(font: ZLLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 30)).width + 20
  223. self.doneBtn.frame = CGRect(x: self.bottomView.bounds.width-doneBtnW-15, y: btnY, width: doneBtnW, height: ZLLayout.bottomToolBtnH)
  224. self.doneBtn.setTitle(doneTitle, for: .normal)
  225. } else {
  226. self.bottomView.isHidden = true
  227. }
  228. }
  229. func dismiss() {
  230. if let nav = self.navigationController {
  231. let vc = nav.popViewController(animated: true)
  232. if vc == nil {
  233. nav.dismiss(animated: true, completion: nil)
  234. }
  235. } else {
  236. self.dismiss(animated: true, completion: nil)
  237. }
  238. }
  239. // MARK: btn actions
  240. @objc func backBtnClick() {
  241. self.dismiss()
  242. }
  243. @objc func selectBtnClick() {
  244. var isSelected = self.selectStatus[self.currentIndex]
  245. self.selectBtn.layer.removeAllAnimations()
  246. if isSelected {
  247. isSelected = false
  248. } else {
  249. self.selectBtn.layer.add(getSpringAnimation(), forKey: nil)
  250. isSelected = true
  251. }
  252. self.selectStatus[self.currentIndex] = isSelected
  253. self.resetSubViewStatus()
  254. }
  255. @objc func doneBtnClick() {
  256. if self.showSelectBtn {
  257. let res = self.datas.enumerated().filter { (index, value) -> Bool in
  258. return self.selectStatus[index]
  259. }.map { (_, v) -> Any in
  260. return v
  261. }
  262. self.doneBlock?(res)
  263. } else {
  264. self.doneBlock?(self.datas)
  265. }
  266. self.dismiss()
  267. }
  268. func tapPreviewCell() {
  269. self.hideNavView = !self.hideNavView
  270. let currentCell = self.collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0))
  271. if let cell = currentCell as? ZLVideoPreviewCell {
  272. if cell.isPlaying {
  273. self.hideNavView = true
  274. }
  275. }
  276. self.navView.isHidden = self.hideNavView
  277. if self.showBottomView {
  278. self.bottomView.isHidden = self.hideNavView
  279. }
  280. }
  281. }
  282. // scroll view delegate
  283. extension ZLImagePreviewController {
  284. public func scrollViewDidScroll(_ scrollView: UIScrollView) {
  285. guard scrollView == self.collectionView else {
  286. return
  287. }
  288. NotificationCenter.default.post(name: ZLPhotoPreviewController.previewVCScrollNotification, object: nil)
  289. let offset = scrollView.contentOffset
  290. var page = Int(round(offset.x / (self.view.bounds.width + ZLPhotoPreviewController.colItemSpacing)))
  291. page = max(0, min(page, self.datas.count-1))
  292. if page == self.currentIndex {
  293. return
  294. }
  295. self.currentIndex = page
  296. self.resetSubViewStatus()
  297. }
  298. public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  299. self.indexBeforOrientationChanged = self.currentIndex
  300. let cell = self.collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0))
  301. if let cell = cell as? ZLGifPreviewCell {
  302. cell.loadGifWhenCellDisplaying()
  303. } else if let cell = cell as? ZLLivePhotoPreviewCell {
  304. cell.loadLivePhotoData()
  305. }
  306. }
  307. }
  308. extension ZLImagePreviewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
  309. public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
  310. return ZLImagePreviewController.colItemSpacing
  311. }
  312. public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
  313. return ZLImagePreviewController.colItemSpacing
  314. }
  315. public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
  316. return UIEdgeInsets(top: 0, left: ZLImagePreviewController.colItemSpacing / 2, bottom: 0, right: ZLImagePreviewController.colItemSpacing / 2)
  317. }
  318. public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  319. return CGSize(width: self.view.bounds.width, height: self.view.bounds.height)
  320. }
  321. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  322. return self.datas.count
  323. }
  324. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  325. let config = ZLPhotoConfiguration.default()
  326. let obj = self.datas[indexPath.row]
  327. let baseCell: ZLPreviewBaseCell
  328. if let asset = obj as? PHAsset {
  329. let model = ZLPhotoModel(asset: asset)
  330. if config.allowSelectGif, model.type == .gif {
  331. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLGifPreviewCell.zl_identifier(), for: indexPath) as! ZLGifPreviewCell
  332. cell.singleTapBlock = { [weak self] in
  333. self?.tapPreviewCell()
  334. }
  335. cell.model = model
  336. baseCell = cell
  337. } else if config.allowSelectLivePhoto, model.type == .livePhoto {
  338. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLLivePhotoPreviewCell.zl_identifier(), for: indexPath) as! ZLLivePhotoPreviewCell
  339. cell.model = model
  340. baseCell = cell
  341. } else if config.allowSelectVideo, model.type == .video {
  342. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLVideoPreviewCell.zl_identifier(), for: indexPath) as! ZLVideoPreviewCell
  343. cell.model = model
  344. baseCell = cell
  345. } else {
  346. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLPhotoPreviewCell.zl_identifier(), for: indexPath) as! ZLPhotoPreviewCell
  347. cell.singleTapBlock = { [weak self] in
  348. self?.tapPreviewCell()
  349. }
  350. cell.model = model
  351. baseCell = cell
  352. }
  353. return baseCell
  354. } else if let image = obj as? UIImage {
  355. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLLocalImagePreviewCell.zl_identifier(), for: indexPath) as! ZLLocalImagePreviewCell
  356. cell.image = image
  357. baseCell = cell
  358. } else if let url = obj as? URL {
  359. let type = self.urlType?(url) ?? ZLURLType.image
  360. if type == .image {
  361. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLNetImagePreviewCell.zl_identifier(), for: indexPath) as! ZLNetImagePreviewCell
  362. cell.image = nil
  363. self.urlImageLoader?(url, cell.preview.imageView, { [weak cell] (progress) in
  364. DispatchQueue.main.async {
  365. cell?.progress = progress
  366. }
  367. }, { [weak cell] in
  368. DispatchQueue.main.async {
  369. cell?.preview.resetSubViewSize()
  370. }
  371. })
  372. baseCell = cell
  373. } else {
  374. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZLNetVideoPreviewCell.zl_identifier(), for: indexPath) as! ZLNetVideoPreviewCell
  375. cell.videoUrl = url
  376. baseCell = cell
  377. }
  378. } else {
  379. #if DEBUG
  380. fatalError("Preview obj must one of PHAsset, UIImage, URL")
  381. #else
  382. return UICollectionViewCell()
  383. #endif
  384. }
  385. baseCell.singleTapBlock = { [weak self] in
  386. self?.tapPreviewCell()
  387. }
  388. (baseCell as? ZLLocalImagePreviewCell)?.longPressBlock = { [weak self] in
  389. self?.showSaveImageAlert()
  390. }
  391. return baseCell
  392. }
  393. public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
  394. if let c = cell as? ZLPreviewBaseCell {
  395. c.resetSubViewStatusWhenCellEndDisplay()
  396. }
  397. }
  398. func showSaveImageAlert() {
  399. func saveImage() {
  400. guard let cell = self.collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0)) as? ZLLocalImagePreviewCell, let image = cell.currentImage else {
  401. return
  402. }
  403. let hud = ZLProgressHUD(style: ZLPhotoConfiguration.default().hudStyle)
  404. hud.show()
  405. ZLPhotoManager.saveImageToAlbum(image: image) { [weak self] (suc, _) in
  406. hud.hide()
  407. if !suc {
  408. showAlertView(localLanguageTextValue(.saveImageError), self)
  409. }
  410. }
  411. }
  412. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  413. let save = UIAlertAction(title: localLanguageTextValue(.save), style: .default) { (_) in
  414. saveImage()
  415. }
  416. let cancel = UIAlertAction(title: localLanguageTextValue(.cancel), style: .cancel, handler: nil)
  417. alert.addAction(save)
  418. alert.addAction(cancel)
  419. self.showDetailViewController(alert, sender: nil)
  420. }
  421. }