UIImageView.swift 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // UIImageView.swift
  3. // Gasteizko Margolariak
  4. //
  5. // Created by Yuji Hato on 11/3/15.
  6. // Copyright © 2015 Yuji Hato. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIImageView {
  10. func setRandomDownloadImage(width: Int, height: Int) {
  11. if self.image != nil {
  12. self.alpha = 1
  13. return
  14. }
  15. self.alpha = 0
  16. let url = NSURL(string: "https://ssl.webpack.de/lorempixel.com/\(width)/\(height)/")!
  17. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  18. configuration.timeoutIntervalForRequest = 15
  19. configuration.timeoutIntervalForResource = 15
  20. configuration.requestCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
  21. let session = NSURLSession(configuration: configuration)
  22. let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
  23. if error != nil {
  24. return
  25. }
  26. if let response = response as? NSHTTPURLResponse {
  27. if response.statusCode / 100 != 2 {
  28. return
  29. }
  30. if let data = data, let image = UIImage(data: data) {
  31. dispatch_async(dispatch_get_main_queue(), { () -> Void in
  32. self.image = image
  33. UIView.animateWithDuration(0.3, animations: { () -> Void in
  34. self.alpha = 1
  35. }) { (finished: Bool) -> Void in
  36. }
  37. })
  38. }
  39. }
  40. })
  41. task.resume()
  42. }
  43. func clipParallaxEffect(baseImage: UIImage?, screenSize: CGSize, displayHeight: CGFloat) {
  44. if let baseImage = baseImage {
  45. if displayHeight < 0 {
  46. return
  47. }
  48. let aspect: CGFloat = screenSize.width / screenSize.height
  49. let imageSize = baseImage.size
  50. let imageScale: CGFloat = imageSize.height / screenSize.height
  51. let cropWidth: CGFloat = floor(aspect < 1.0 ? imageSize.width * aspect : imageSize.width)
  52. let cropHeight: CGFloat = floor(displayHeight * imageScale)
  53. let left: CGFloat = (imageSize.width - cropWidth) / 2
  54. let top: CGFloat = (imageSize.height - cropHeight) / 2
  55. let trimRect : CGRect = CGRectMake(left, top, cropWidth, cropHeight)
  56. self.image = baseImage.trim(trimRect: trimRect)
  57. self.frame = CGRectMake(0, 0, screenSize.width, displayHeight)
  58. }
  59. }
  60. }