Advertisement
Guest User

Untitled

a guest
May 3rd, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 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), size)
  13. }
  14.  
  15. func RBSquareImage(image: UIImage) -> UIImage? {
  16. var originalWidth = image.size.width
  17. var originalHeight = image.size.height
  18.  
  19. var edge: CGFloat
  20. if originalWidth > originalHeight {
  21. edge = originalHeight
  22. } else {
  23. edge = originalWidth
  24. }
  25.  
  26. var posX = (originalWidth - edge) / 2.0
  27. var posY = (originalHeight - edge) / 2.0
  28.  
  29. var cropSquare = CGRectMake(posX, posY, edge, edge)
  30.  
  31. var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
  32. return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
  33. }
  34.  
  35. func RBResizeImage(image: UIImage?, targetSize: CGSize) -> UIImage? {
  36. if let image = image {
  37. let size = image.size
  38.  
  39. let widthRatio = targetSize.width / image.size.width
  40. let heightRatio = targetSize.height / image.size.height
  41.  
  42. // Figure out what our orientation is, and use that to form the rectangle
  43. var newSize: CGSize
  44. if(widthRatio > heightRatio) {
  45. newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
  46. } else {
  47. newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
  48. }
  49.  
  50. // This is the rect that we've calculated out and this is what is actually used below
  51. let rect = CGRectMake(0, 0, newSize.width, newSize.height)
  52.  
  53. // Actually do the resizing to the rect using the ImageContext stuff
  54. UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
  55. image.drawInRect(rect)
  56. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  57. UIGraphicsEndImageContext()
  58.  
  59. return newImage
  60. } else {
  61. return nil
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement