Skip to content

Instantly share code, notes, and snippets.

@mustafaibrahim989
Last active January 26, 2016 10:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustafaibrahim989/8806941 to your computer and use it in GitHub Desktop.
Save mustafaibrahim989/8806941 to your computer and use it in GitHub Desktop.
Image cropping with resizing
//
// UIImage+MICropping.m
// Mustafa Ibrahim
//
// Created by Mustafa Ibrahim on 2/4/14.
// Copyright (c) 2014 Mustafa Ibrahim. All rights reserved.
//
#import "UIImage+MICropping.h"
@implementation UIImage (MICropping)
- (UIImage *)squareImagescaledToSize:(CGSize)newSize
{
double ratio;
double delta;
CGPoint offset;
//make a new square size, that is the resized imaged width
CGSize sz = CGSizeMake(newSize.width, newSize.width);
//figure out if the picture is landscape or portrait, then
//calculate scale factor and offset
if (self.size.width > self.size.height) {
ratio = newSize.width / self.size.width;
delta = (ratio*self.size.width - ratio*self.size.height);
offset = CGPointMake(delta/2, 0);
} else {
ratio = newSize.width / self.size.height;
delta = (ratio*self.size.height - ratio*self.size.width);
offset = CGPointMake(0, delta/2);
}
//make the final clipping rect based on the calculated values
CGRect clipRect = CGRectMake(-offset.x, -offset.y,
(ratio * self.size.width) + delta,
(ratio * self.size.height) + delta);
//start a new context, with scale factor 0.0 so retina displays get
//high quality image
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(sz, YES, 0.0);
} else {
UIGraphicsBeginImageContext(sz);
}
UIRectClip(clipRect);
[self drawInRect:clipRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
@end
//
// UIImage+MICropping.h
// Mustafa Ibrahim
//
// Created by Mustafa Ibrahim on 2/4/14.
// Copyright (c) 2014 Mustafa Ibrahim. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (MICropping)
- (UIImage *)squareImagescaledToSize:(CGSize)newSize;
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment