Skip to content

Instantly share code, notes, and snippets.

@laevandus
Created November 28, 2020 11: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 laevandus/21cefc7e66be57c8692f01ad95a4e167 to your computer and use it in GitHub Desktop.
Save laevandus/21cefc7e66be57c8692f01ad95a4e167 to your computer and use it in GitHub Desktop.
import CoreGraphics
struct ImageScaler {
static func scaleToFill(_ image: CGImage, from fromRect: CGRect = .zero, in targetSize: CGSize) -> CGImage? {
let imageSize = CGSize(width: image.width, height: image.height)
let rect = fromRect.isEmpty ? CGRect(origin: .zero, size: imageSize) : fromRect
let scaledRect = rect.scaled(toFillSize: targetSize)
return scale(image, fromRect: scaledRect, in: targetSize)
}
private static func scale(_ image: CGImage, fromRect: CGRect = .zero, in targetSize: CGSize) -> CGImage? {
let makeCroppedCGImage: (CGImage) -> CGImage? = { cgImage in
guard !fromRect.isEmpty else { return cgImage }
return cgImage.cropping(to: fromRect)
}
guard let croppedImage = makeCroppedCGImage(image) else { return nil }
let context = CGContext(data: nil,
width: Int(targetSize.width),
height: Int(targetSize.height),
bitsPerComponent: croppedImage.bitsPerComponent,
bytesPerRow: croppedImage.bytesPerRow,
space: croppedImage.colorSpace ?? CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: croppedImage.bitmapInfo.rawValue)
context?.interpolationQuality = .high
context?.draw(croppedImage, in: CGRect(origin: .zero, size: targetSize))
return context?.makeImage()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment