Skip to content

Instantly share code, notes, and snippets.

@huangenyan
Created April 30, 2019 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huangenyan/cfb21cbb06685d0187538a91652f74b4 to your computer and use it in GitHub Desktop.
Save huangenyan/cfb21cbb06685d0187538a91652f74b4 to your computer and use it in GitHub Desktop.
import UIKit
extension UIImage {
func resizeImage(size: CGSize) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(size, true, 1)
self.draw(in: CGRect(origin: CGPoint.zero, size: size))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage
}
func cropImage(rect: CGRect) -> UIImage? {
guard let cutImageRef: CGImage = self.cgImage?.cropping(to: rect) else {
return nil
}
let croppedImage: UIImage = UIImage(cgImage: cutImageRef, scale: self.scale, orientation: self.imageOrientation)
return croppedImage
}
func rotateImage(orientation: UIImage.Orientation) -> UIImage? {
let newSize: CGSize = {
switch orientation {
case .left, .leftMirrored, .right, .rightMirrored:
return CGSize(width: self.size.height, height: self.size.width)
default:
return self.size
}
}()
UIGraphicsBeginImageContextWithOptions(newSize, true, 1)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
switch orientation {
case .left:
context.rotate(by: -CGFloat.pi / 2)
self.draw(at: CGPoint(x: -self.size.width, y: 0))
case .leftMirrored:
context.scaleBy(x: -1, y: 1)
context.rotate(by: CGFloat.pi / 2)
self.draw(at: CGPoint(x: 0, y: 0))
case .right:
context.rotate(by: CGFloat.pi / 2)
self.draw(at: CGPoint(x: 0, y: -self.size.height))
case .rightMirrored:
context.scaleBy(x: -1, y: 1)
context.rotate(by: -CGFloat.pi / 2)
self.draw(at: CGPoint(x: -self.size.width, y: -self.size.height))
case .upMirrored:
context.scaleBy(x: -1, y: 1)
self.draw(at: CGPoint(x: -self.size.width, y: 0))
case .down:
context.rotate(by: CGFloat.pi)
self.draw(at: CGPoint(x: -self.size.width, y: -self.size.height))
case .downMirrored:
context.scaleBy(x: 1, y: -1)
self.draw(at: CGPoint(x: 0, y: -self.size.height))
default:
break
}
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment