Advertisement
Guest User

Untitled

a guest
May 28th, 2015
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. //
  2. // RBResizer.swift
  3. // Locker
  4. //
  5. // Created by Hampton Catlin on 6/20/14.
  6. // Copyright (c) 2014 rarebit. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10.  
  11. func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage {
  12. return RBResizeImage(RBSquareImage(image), targetSize: size)
  13. }
  14.  
  15. func RBSquareImage(image: UIImage) -> UIImage {
  16. var originalWidth = image.size.width
  17. var originalHeight = image.size.height
  18. var x: CGFloat = 0.0
  19. var y: CGFloat = 0.0
  20. var edge: CGFloat = 0.0
  21.  
  22. if (originalWidth > originalHeight) {
  23. // landscape
  24. edge = originalHeight
  25. x = (originalWidth - edge) / 2.0
  26. y = 0.0
  27.  
  28. } else if (originalHeight > originalWidth) {
  29. // portrait
  30. edge = originalWidth
  31. x = 0.0
  32. y = (originalHeight - originalWidth) / 2.0
  33. } else {
  34. // square
  35. edge = originalWidth
  36. }
  37.  
  38. var cropSquare = CGRectMake(x, y, edge, edge)
  39. var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
  40.  
  41. return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)!
  42. }
  43.  
  44. func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
  45. let size = image.size
  46.  
  47. let widthRatio = targetSize.width / image.size.width
  48. let heightRatio = targetSize.height / image.size.height
  49.  
  50. // Figure out what our orientation is, and use that to form the rectangle
  51. var newSize: CGSize
  52. if(widthRatio > heightRatio) {
  53. newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
  54. } else {
  55. newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
  56. }
  57.  
  58. // This is the rect that we've calculated out and this is what is actually used below
  59. let rect = CGRectMake(0, 0, newSize.width, newSize.height)
  60.  
  61. // Actually do the resizing to the rect using the ImageContext stuff
  62. UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
  63. image.drawInRect(rect)
  64. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  65. UIGraphicsEndImageContext()
  66.  
  67. return newImage
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement