Skip to content

Instantly share code, notes, and snippets.

@artemkrachulov
Last active July 21, 2016 11:30
Show Gist options
  • Save artemkrachulov/c81cbc85e36e516f802b41efff6e749e to your computer and use it in GitHub Desktop.
Save artemkrachulov/c81cbc85e36e516f802b41efff6e749e to your computer and use it in GitHub Desktop.
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)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment