artemkrachulov
7/21/2016 - 11:29 AM

Returns image cropped from selected rectangle

Returns image cropped from selected rectangle

//
//  UIImage+imageInRect.swift
//
//  Created by Artem Krachulov
//  Copyright (c) 2016 Artem Krachulov. All rights reserved.
//	http://www.artemkrachulov.com
//

import UIKit

extension UIImage {
  
  /// Returns image cropped from selected rectangle.
  ///
  /// Usage:
  ///
  ///   let image = UIImage(named: "__NAME__")
  ///		image?.imageInRect(CGRectMake(50,50,100,100))
  public func imageInRect(rect: CGRect, currentContext: Bool = false) -> UIImage? {
    if currentContext {
      
      // Create the bitmap context
      UIGraphicsBeginImageContext(rect.size)
      
      guard let context = UIGraphicsGetCurrentContext() else {
        return nil
      }
      
      // Sets the clipping path to the intersection of the current clipping path with the area defined by the specified rectangle.
      CGContextClipToRect(context, CGRect(origin: CGPointZero, size: rect.size))
      
      drawInRect(CGRect(origin: CGPointMake(-rect.origin.x, -rect.origin.y), size: size))
      
      // Returns an image based on the contents of the current bitmap-based graphics context.
      let image = UIGraphicsGetImageFromCurrentImageContext()
      
      UIGraphicsEndImageContext()
      
      return image
      
    } else {
      
      guard let imageRef = CGImageCreateWithImageInRect(CGImage, rect) else {
        return nil
      }
      
      // Returns an image based on the imageRef and rotate back to the original orientation
      return UIImage(CGImage: imageRef, scale: scale, orientation: imageOrientation)
    }
  }
}