Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active October 25, 2020 11:19
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 laevandus/ac352199893015d8e89ecd924e64287c to your computer and use it in GitHub Desktop.
Save laevandus/ac352199893015d8e89ecd924e64287c to your computer and use it in GitHub Desktop.
private static func scale(_ image: UIImage, fromRect: CGRect = .zero, targetSize: CGSize) -> UIImage {
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { context in
// UIImage and CGContext coordinates are flipped.
var transform = CGAffineTransform(translationX: 0.0, y: targetSize.height)
transform = transform.scaledBy(x: 1, y: -1)
context.cgContext.concatenate(transform)
// UIImage -> cropped CGImage
let makeCroppedCGImage: (UIImage) -> CGImage? = { image in
guard let cgImage = image.cgImage else { return nil }
guard !fromRect.isEmpty else { return cgImage }
return cgImage.cropping(to: fromRect)
}
if let cgImage = makeCroppedCGImage(image) {
context.cgContext.draw(cgImage, in: CGRect(origin: .zero, size: targetSize))
}
else if let ciImage = image.ciImage {
var transform = CGAffineTransform(translationX: 0.0, y: image.size.height)
transform = transform.scaledBy(x: 1, y: -1)
let adjustedFromRect = fromRect.applying(transform)
let ciContext = CIContext(cgContext: context.cgContext, options: nil)
ciContext.draw(ciImage, in: CGRect(origin: .zero, size: targetSize), from: adjustedFromRect)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment