-
-
Save vdeep/de96dba6787ea990d482fb7a04f099aa to your computer and use it in GitHub Desktop.
UIImage Resize/Scaling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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