PPPhotoViewCell.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import UIKit
  2. import PhotosUI
  3. /**
  4. Cell representing photo asset in Assets Collection Controller.
  5. */
  6. class PPPhotoViewCell: PPCheckedViewCell {
  7. var asset:PHAsset?
  8. var calcSize:CGSize?
  9. func set(_ image: PHAsset) {
  10. if asset != image || calcSize != calcNewSizeForAsset() {
  11. self.asset = image
  12. self.calcSize = calcNewSizeForAsset()
  13. let options: PHImageRequestOptions = PHImageRequestOptions.init()
  14. options.isNetworkAccessAllowed = true
  15. options.resizeMode = .fast
  16. PHImageManager.default().requestImage(for: image, targetSize: self.calcSize!, contentMode: .aspectFit, options: options) { (loadedImage, info) in
  17. if loadedImage != nil {
  18. let photo = UIImageView( image: loadedImage)
  19. photo.contentMode = .scaleAspectFit
  20. photo.clipsToBounds = true
  21. self.backgroundView = photo
  22. } else {
  23. let photo = UIImageView( image: nil)
  24. photo.contentMode = .scaleAspectFit
  25. photo.clipsToBounds = true
  26. photo.backgroundColor = UIColor.black
  27. self.backgroundView = photo
  28. }
  29. }
  30. }
  31. self.setupCheckmark()
  32. }
  33. func calcNewSizeForAsset() -> CGSize {
  34. let widthFactor = CGFloat((asset?.pixelWidth)!) / self.frame.size.width
  35. let heightFactor = CGFloat((asset?.pixelHeight)!) / self.frame.size.height
  36. var resizeFactor = widthFactor
  37. if CGFloat((asset?.pixelHeight)!) > CGFloat((asset?.pixelWidth)!) {
  38. resizeFactor = heightFactor
  39. }
  40. return CGSize(width: (CGFloat((asset?.pixelWidth)!)/resizeFactor) * 3.0, height: (CGFloat((asset?.pixelHeight)!)/resizeFactor) * 3.0)
  41. }
  42. }