Skip to content

Instantly share code, notes, and snippets.

@iroller
Forked from HamptonMakes/RBResizer.swift
Last active January 8, 2020 14:06
Show Gist options
  • Save iroller/390f4e20736db3bc39a0 to your computer and use it in GitHub Desktop.
Save iroller/390f4e20736db3bc39a0 to your computer and use it in GitHub Desktop.
Swift Image Resizer
//
// RBResizer.swift
// Locker
//
// Created by Hampton Catlin on 6/20/14.
// Copyright (c) 2014 rarebit. All rights reserved.
//
import UIKit
func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage? {
return RBResizeImage(RBSquareImage(image), targetSize: size)
}
func RBSquareImage(image: UIImage) -> UIImage? {
let originalWidth = image.size.width
let originalHeight = image.size.height
var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}
let posX = (originalWidth - edge) / 2.0
let posY = (originalHeight - edge) / 2.0
let cropSquare = CGRectMake(posX, posY, edge, edge)
let imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
return UIImage(CGImage: imageRef!, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)
}
func RBResizeImage(image: UIImage?, targetSize: CGSize) -> UIImage? {
if let image = image {
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
} else {
return nil
}
}
@Pikaurd
Copy link

Pikaurd commented Sep 22, 2015

UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale) = UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
Do same thing, and thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment