Skip to content

Instantly share code, notes, and snippets.

@westerlund
Forked from HamptonMakes/RBResizer.swift
Created December 21, 2014 16:27
Show Gist options
  • Save westerlund/9e357a50315a7d9fe419 to your computer and use it in GitHub Desktop.
Save westerlund/9e357a50315a7d9fe419 to your computer and use it in GitHub Desktop.
//
// 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), size)
}
func RBSquareImage(image: UIImage) -> UIImage? {
var originalWidth = image.size.width
var originalHeight = image.size.height
var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}
var posX = (originalWidth - edge) / 2.0
var posY = (originalHeight - edge) / 2.0
var cropSquare = CGRectMake(posX, posY, edge, edge)
var 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, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
} else {
return nil
}
}
@westerlund
Copy link
Author

updated to work with swift 1.1

@markotl88
Copy link

I don't know why it doesn't work for me. Example: my origin image size is 480x640, so cropSquare is 480x480, but instead of getting same size for imageRef, I'm getting 480x400, and then function is returning "img" with size 200x240 (?!). But if I use 0 instead of posY in CGRectMake (posX, 0, edge, edge) everything is fine (returning image size is 480x480), but the image is not centered but is cropped from the top, of course. Can someone help me?

@jchesne
Copy link

jchesne commented Mar 12, 2015

markotl88, take a look at this comment section :
https://gist.github.com/hcatlin/180e81cd961573e3c54d

Copy link

ghost commented Oct 19, 2015

How do I make this work? How do I use it?

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