Skip to content

Instantly share code, notes, and snippets.

@temoki
Created October 23, 2017 02:17
Show Gist options
  • Save temoki/48f17e3a7176dc9330198366782cfeab to your computer and use it in GitHub Desktop.
Save temoki/48f17e3a7176dc9330198366782cfeab to your computer and use it in GitHub Desktop.
UIImage+Extension
extension UIImage {
public func cropped(to rect: CGRect) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(rect.size, true, scale)
draw(at: rect.origin.applying(CGAffineTransform(scaleX: -1, y: -1)))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public func squareCropped() -> UIImage? {
let rect = size.width > size.height
? CGRect(x: (size.width - size.height) * 0.5, y: 0, width: size.height, height: size.height)
: CGRect(x: 0, y: (size.height - size.width) * 0.5, width: size.width, height: size.width)
return cropped(to: rect)
}
public func resized(to size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, true, scale)
draw(in: CGRect(origin: .zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment