Skip to content

Instantly share code, notes, and snippets.

@marcosgriselli
Last active February 2, 2024 07:04
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save marcosgriselli/00ab6c68f48ccaeb110afc82786767ec to your computer and use it in GitHub Desktop.
Save marcosgriselli/00ab6c68f48ccaeb110afc82786767ec to your computer and use it in GitHub Desktop.
UIImage Resize/Scaling
//
// UIImage+Resize.swift
//
// Created by Marcos Griselli on 6/9/17.
// Copyright © 2017 Marcos Griselli. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
class func resize(image: UIImage, targetSize: CGSize) -> UIImage {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
var newSize: CGSize
if widthRatio > heightRatio {
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
} else {
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
}
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
class func scale(image: UIImage, by scale: CGFloat) -> UIImage? {
let size = image.size
let scaledSize = CGSize(width: size.width * scale, height: size.height * scale)
return UIImage.resize(image: image, targetSize: scaledSize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment