How to Crop a UiImage to specific Size? - ios

Hi I am working with the UIimage, I need to crop my image to specific size, Suppose my specific size width is equal to device width and height is fixed 200.
I tried in Google lot of examples but non of those not working for me, I tried below samples
-(UIImage *)resizeImage:(UIImage *)image
{
float h=200;
float w=400;
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = h;
float maxWidth = w;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.8;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
//UIGraphicsBeginImageContextWithOptions(rect.size,NO,0.0);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
Below is my actual image
After cropping I am getting like below
All of my examples are stretching the image But i want with out stretching need to scale the image.Where i am missing?Please help me.

The code you are using will resize your image, We use it for image compression or image resizing.
If you want to crop an Image there are two way.
1)Allow user to edit when image is selected.
You can achieve this by adding allowEditing property to picker like,
pickerView.allowEditing = true
This will give you rectangle to crop image, you can retrieve edited image from didFinish method of picker view
2)Programatically
To crop image programatically you need to pass frame for cropping.
Here is the function i am using
func croppImage(originalImage:UIImage, toRect rect:CGRect) -> UIImage{
var imageRef:CGImageRef = CGImageCreateWithImageInRect(originalImage.CGImage, rect)
var croppedimage:UIImage = UIImage(CGImage:imageRef)
return croppedimage
}
The above code will return you cropped image.

These will crop your image into size you required.
- (CGImageRef)newTransformedImage:(CGAffineTransform)transform
sourceImage:(CGImageRef)sourceImage
sourceSize:(CGSize)sourceSize
sourceOrientation:(UIImageOrientation)sourceOrientation
outputWidth:(CGFloat)outputWidth
cropSize:(CGSize)cropSize
imageViewSize:(CGSize)imageViewSize
{
CGImageRef source = [self newScaledImage:sourceImage
withOrientation:sourceOrientation
toSize:sourceSize
withQuality:kCGInterpolationNone];
CGFloat aspect = cropSize.height/cropSize.width;
CGSize outputSize = CGSizeMake(outputWidth, outputWidth*aspect);
CGContextRef context = CGBitmapContextCreate(NULL,
outputSize.width,
outputSize.height,
CGImageGetBitsPerComponent(source),
0,
CGImageGetColorSpace(source),
CGImageGetBitmapInfo(source));
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
CGContextFillRect(context, CGRectMake(0, 0, outputSize.width, outputSize.height));
CGAffineTransform uiCoords = CGAffineTransformMakeScale(outputSize.width / cropSize.width,
outputSize.height / cropSize.height);
uiCoords = CGAffineTransformTranslate(uiCoords, cropSize.width/2.0, cropSize.height / 2.0);
uiCoords = CGAffineTransformScale(uiCoords, 1.0, -1.0);
CGContextConcatCTM(context, uiCoords);
CGContextConcatCTM(context, transform);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(-imageViewSize.width/2.0,
-imageViewSize.height/2.0,
imageViewSize.width,
imageViewSize.height)
, source);
CGImageRef resultRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGImageRelease(source);
return resultRef;
}
- (CGImageRef)newScaledImage:(CGImageRef)source withOrientation:(UIImageOrientation)orientation toSize:(CGSize)size withQuality:(CGInterpolationQuality)quality
{
CGSize srcSize = size;
CGFloat rotation = 0.0;
switch(orientation)
{
case UIImageOrientationUp: {
rotation = 0;
} break;
case UIImageOrientationDown: {
rotation = M_PI;
} break;
case UIImageOrientationLeft:{
rotation = M_PI_2;
srcSize = CGSizeMake(size.height, size.width);
} break;
case UIImageOrientationRight: {
rotation = -M_PI_2;
srcSize = CGSizeMake(size.height, size.width);
} break;
default:
break;
}
CGContextRef context = CGBitmapContextCreate(NULL,
size.width,
size.height,
8, //CGImageGetBitsPerComponent(source),
0,
CGImageGetColorSpace(source),
(CGBitmapInfo)kCGImageAlphaNoneSkipFirst //CGImageGetBitmapInfo(source)
);
CGContextSetInterpolationQuality(context, quality);
CGContextTranslateCTM(context, size.width/2, size.height/2);
CGContextRotateCTM(context,rotation);
CGContextDrawImage(context, CGRectMake(-srcSize.width/2 ,
-srcSize.height/2,
srcSize.width,
srcSize.height),
source);
CGImageRef resultRef = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return resultRef;
}
///where you want to crop.
CGImageRef imageRef = [self newTransformedImage:transform
sourceImage:self.image.CGImage
sourceSize:self.image.size
sourceOrientation:self.image.imageOrientation
outputWidth:self.image.size.width
cropSize:self.photoView.cropView.frame.size
imageViewSize:self.photoView.photoContentView.bounds.size];
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
Thank you. Enjoy Coding :)

Related

iOS UIImage dimension change not working

I am resizing a UIImage by changing the dimension. But it shows different dimension. For iPhone 6, I choose 1.25 time than the screen dimension which should come 937*1667. But after completing my resize operation is becomes 938*1251. I need it in declared dimension.
My code is :
NSData *imageData;
imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];
CGSize sz;
sz.width=((isIphone4||isIphone5)?320*2.3:iPhone6?750*1.25:414*1.8);
sz.height=((isIphone4||isIphone5)?568*2.3:iPhone6?667*1.25:768*1.8);
if([imageData length]/1024>400)
image=[self resizeImage:image scaledToSize:sz];
//function call
-(UIImage *)resizeImage:(UIImage *)image scaledToSize:(CGSize)targetSize
{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = targetSize.height;
float maxWidth = targetSize.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.50;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
What could be solution for correct dimension ?
Yes, finally i solved it after few hours. I tried in a wrong way. Actually, the dimension can not be fixed when we resize in a particular memory size. The following method convert the image into ranged size (Byte) and the dimension will be define by the method itself.
NSData *imageData;
imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((image), 1.0)];
CGFloat scale= (400*1024)/(CGFloat)[imageData length];
UIImage *small_image=[UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
imageData = UIImageJPEGRepresentation(small_image, scale);

IOS How to resize image according to actual image ratio and give custom size?

Resize UIImage with custom size by checking actual image ratio for reducing image size. I have already tried this UIImageJPEGRepresentation(Image, 0.8); but problem with this is that image quality is reducing. Any help would be really appreciated. Thank you
Pass UIImage to below method which resize your image with custom height/width and you can also give compression value of image for reducing image size and Check image size before and after resizing.
Here is sample method-
-(UIImage *)resizeImage:(UIImage *)image
{
NSInteger imageActualSize = UIImageJPEGRepresentation(image,1).length;
NSLog(#"size of IMAGE before resizing: %# ", [NSByteCountFormatter stringFromByteCount:imageActualSize countStyle:NSByteCountFormatterCountStyleFile]);
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 400.0; // your custom height
float maxWidth = 350; // your custom width
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.5;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
NSInteger imageReduceSize = imageData.length;
NSLog(#"size of IMAGE after resizing: %# ",[NSByteCountFormatter stringFromByteCount:imageReduceSize countStyle:NSByteCountFormatterCountStyleFile]);
return [UIImage imageWithData:imageData];
}
This will help you..:)
+ (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
very easy way to do this.

Resize uiimage not give me exact new size after resize it

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height)); //CGSize is 51*51
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
NSLog(#"size of resizeimage is %#",NSStringFromCGSize(newImage.size)); // here i get 102*102
return newImage;
}
I enter cgsize that is 51*51,
and after resize when i check the size its give me 102*102.
why?Please solve my problem.
Look at your UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);, from Apple documentation the scale parameter means :
The scale factor to apply to the bitmap. If you specify a value of 0.0, the scale factor is set to the scale factor of the device’s main screen.
So if it's a retina display, it's normal.
I have followed this method to resize image
-(UIImage *)resizeImage:(UIImage *)image newSize:(CGSize)newSize
{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = newSize.height;
float maxWidth = newSize.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth)
{
if(imgRatio < maxRatio)
{
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio)
{
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else
{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSLog(#"size of resizeimage is %#",NSStringFromCGSize(img.size));
NSLog(#"size of original is %#",NSStringFromCGSize(image.size));
return img;
}

Cropping UIimage in IOS

I am very new to IOS and the first task given to me is Image cropping. means If I am using an image as banner image and the given frame size is more then or smaller thn the size of the image . my code should automatically resize image in respective aspect ratio of the image and then set image in that frame.
I have done so much R&D and after that i have written code.
-(UIImage *)MyScaleNEwMethodwithImage:(UIImage *)image andframe:(CGRect)frame{
float bmHeight= image.size.height;
float bmWidth= image.size.width;
UIImage *RecievedImage=image;
if (bmHeight>bmWidth) {
float ratio = frame.size.height/frame.size.width;
float newbmHeight = ratio*bmWidth;
float cropedHeight= (bmHeight-newbmHeight)/2;
if (cropedHeight<0) {
float ratio1= frame.size.width/frame.size.height;
float newbmHeight1= (ratio1*bmHeight);
float cropedimageHeight1 = (bmWidth- newbmHeight1)/2;
CGRect cliprect = CGRectMake(cropedimageHeight1, 0,bmWidth-cropedimageHeight1,bmHeight);
CGImageRef imref = CGImageCreateWithImageInRect([image CGImage],cliprect);
UIImage *newSubImage = [UIImage imageWithCGImage:imref];
return newSubImage;
}
else
{
CGRect cliprect = CGRectMake(0,cropedHeight,bmWidth,bmHeight-cropedHeight);
CGImageRef imref = CGImageCreateWithImageInRect([image CGImage],cliprect);
UIImage *newSubImage = [UIImage imageWithCGImage:imref];
return newSubImage;
}
}
else
{
float ratio = frame.size.height/frame.size.width;
float newbmHeight = ratio*bmHeight;
float cropedHeight= (bmHeight-newbmHeight)/4;
if (cropedHeight<0) {
float ratio1= frame.size.width/frame.size.height;
float newbmHeight1= (ratio1*bmWidth);
float cropedimageHeight1 = (bmWidth- newbmHeight1)/2;
UIImageView *DummyImage=[[UIImageView alloc]initWithFrame:CGRectMake(0,cropedimageHeight1,bmWidth,(bmHeight-cropedimageHeight1))];
[DummyImage setImage:RecievedImage];
CGImageRef imageRef = CGImageCreateWithImageInRect([DummyImage.image CGImage], CGRectMake(0,cropedimageHeight1/2,bmWidth/2,(bmHeight-cropedimageHeight1)/2));
// or use the UIImage wherever you like
[DummyImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
UIImage *ScaledImage=[UIImage imageWithCGImage:imageRef];
return ScaledImage;
} else {
UIImageView *DummyImage=[[UIImageView alloc]initWithFrame:CGRectMake(cropedHeight,0,bmWidth-cropedHeight,bmHeight)];
[DummyImage setImage:RecievedImage];
CGImageRef imageRef = CGImageCreateWithImageInRect([DummyImage.image CGImage],CGRectMake(cropedHeight,2*cropedHeight,(bmWidth-cropedHeight),bmHeight/2));
// or use the UIImage wherever you like
[DummyImage setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
UIImage *ScaledImage=[UIImage imageWithCGImage:imageRef];
return ScaledImage;
}
}
}
In my frame i am getting required image but when screen changes i can see full image. i want to cut the unwanted image.
Thise piece of code may help you out
-(CGRect) cropImage:(CGRect)frame
{
NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, #"content mode should be aspect fit");
CGFloat wScale = self.bounds.size.width / self.image.size.width;
CGFloat hScale = self.bounds.size.height / self.image.size.height;
float x, y, w, h, offset;
if (wScale<hScale) {
offset = (self.bounds.size.height - (self.image.size.height*widthScale))/2;
x = frame.origin.x / wScale;
y = (frame.origin.y-offset) / wScale;
w = frame.size.width / wScale;
h = frame.size.height / wScale;
} else {
offset = (self.bounds.size.width - (self.image.size.width*heightScale))/2;
x = (frame.origin.x-offset) / hScale;
y = frame.origin.y / hScale;
w = frame.size.width / hScale;
h = frame.size.height / hScale;
}
return CGRectMake(x, y, w, h);
}
The code which I had referred to crop the image as per aspect ratio is :
typedef enum {
MGImageResizeCrop,
MGImageResizeCropStart,
MGImageResizeCropEnd,
MGImageResizeScale
} MGImageResizingMethod;
- (UIImage *)imageToFitSize:(CGSize)fitSize method:(MGImageResizingMethod)resizeMethod
{
float imageScaleFactor = 1.0;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([self respondsToSelector:#selector(scale)]) {
imageScaleFactor = [self scale];
}
#endif
float sourceWidth = [self size].width * imageScaleFactor;
float sourceHeight = [self size].height * imageScaleFactor;
float targetWidth = fitSize.width;
float targetHeight = fitSize.height;
BOOL cropping = !(resizeMethod == MGImageResizeScale);
// Calculate aspect ratios
float sourceRatio = sourceWidth / sourceHeight;
float targetRatio = targetWidth / targetHeight;
// Determine what side of the source image to use for proportional scaling
BOOL scaleWidth = (sourceRatio <= targetRatio);
// Deal with the case of just scaling proportionally to fit, without cropping
scaleWidth = (cropping) ? scaleWidth : !scaleWidth;
// Proportionally scale source image
float scalingFactor, scaledWidth, scaledHeight;
if (scaleWidth) {
scalingFactor = 1.0 / sourceRatio;
scaledWidth = targetWidth;
scaledHeight = round(targetWidth * scalingFactor);
} else {
scalingFactor = sourceRatio;
scaledWidth = round(targetHeight * scalingFactor);
scaledHeight = targetHeight;
}
float scaleFactor = scaledHeight / sourceHeight;
// Calculate compositing rectangles
CGRect sourceRect, destRect;
if (cropping) {
destRect = CGRectMake(0, 0, targetWidth, targetHeight);
float destX, destY;
if (resizeMethod == MGImageResizeCrop) {
// Crop center
destX = round((scaledWidth - targetWidth) / 2.0);
destY = round((scaledHeight - targetHeight) / 2.0);
} else if (resizeMethod == MGImageResizeCropStart) {
// Crop top or left (prefer top)
if (scaleWidth) {
// Crop top
destX = 0.0;
destY = 0.0;
} else {
// Crop left
destX = 0.0;
destY = round((scaledHeight - targetHeight) / 2.0);
}
} else if (resizeMethod == MGImageResizeCropEnd) {
// Crop bottom or right
if (scaleWidth) {
// Crop bottom
destX = round((scaledWidth - targetWidth) / 2.0);
destY = round(scaledHeight - targetHeight);
} else {
// Crop right
destX = round(scaledWidth - targetWidth);
destY = round((scaledHeight - targetHeight) / 2.0);
}
}
sourceRect = CGRectMake(destX / scaleFactor, destY / scaleFactor,
targetWidth / scaleFactor, targetHeight / scaleFactor);
} else {
sourceRect = CGRectMake(0, 0, sourceWidth, sourceHeight);
destRect = CGRectMake(0, 0, scaledWidth, scaledHeight);
}
// Create appropriately modified image.
UIImage *image = nil;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0) {
UIGraphicsBeginImageContextWithOptions(destRect.size, NO, 0.0); // 0.0 for scale means "correct scale for device's main screen".
CGImageRef sourceImg = CGImageCreateWithImageInRect([self CGImage], sourceRect); // cropping happens here.
image = [UIImage imageWithCGImage:sourceImg scale:0.0 orientation:self.imageOrientation]; // create cropped UIImage.
[image drawInRect:destRect]; // the actual scaling happens here, and orientation is taken care of automatically.
CGImageRelease(sourceImg);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
#endif
if (!image) {
// Try older method.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, fitSize.width, fitSize.height, 8, (fitSize.width * 4),
colorSpace, kCGImageAlphaPremultipliedLast);
CGImageRef sourceImg = CGImageCreateWithImageInRect([self CGImage], sourceRect);
CGContextDrawImage(context, destRect, sourceImg);
CGImageRelease(sourceImg);
CGImageRef finalImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
image = [UIImage imageWithCGImage:finalImage];
CGImageRelease(finalImage);
}
return image;
}
Check if this helps you.

how to draw UIImage image such as fit out style

I want to get the thumbnail from the jpg file and display as a UIImage. The display style is fit out mode, such as the UIViewContentModeScaleAspectFill. below is the sample code, but it is too complicate.
-(UIImage*)scaleToSize:(CGSize)size
{
CGFloat width = CGImageGetWidth(self.CGImage);
CGFloat height = CGImageGetHeight(self.CGImage);
NSLog(#"size w=%f, h=%f, image w=%f, h=%f", size.width, size.height, width, height);
float verticalRadio = size.height*1.0/height;
float horizontalRadio = size.width*1.0/width;
float radio = 1;
if(verticalRadio>1 && horizontalRadio>1)
{
radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
}
else
{
radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
}
width = width*radio;
height = height*radio;
NSLog(#"width=%f, height=%f", width, height);
int xPos = (size.width - width)/2;
int yPos = (size.height-height)/2;
NSLog(#"xpos=%d, ypos=%d", xPos, yPos);
CGSize sz = CGSizeMake(width, height);
UIGraphicsBeginImageContext(sz);
//
[self drawInRect:CGRectMake(0, 0, width, height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rt = CGRectMake(-xPos, -yPos, size.width, size.height);
UIImage* thub = [scaledImage getSubImage:rt];
scaledImage = nil;
return thub;
}
- (UIImage *)getSubImage:(CGRect) rect{
CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
CGRect smallBounds = CGRectMake(rect.origin.x, rect.origin.y, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
NSLog(#"small bounds x=%f, y=%f, w=%f, h=%f", smallBounds.origin.x, smallBounds.origin.y, smallBounds.size.width, smallBounds.size.height);
UIGraphicsBeginImageContext(smallBounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, smallBounds, subImageRef);
UIImage* smallImg = [UIImage imageWithCGImage:subImageRef];
UIGraphicsEndImageContext();
return smallImg;
}
I have update the method:
-(UIImage*)getSubImage:(CGSize)size
{
CGFloat width = CGImageGetWidth(self.CGImage);
CGFloat height = CGImageGetHeight(self.CGImage);
float verticalRadio = size.height*1.0/height;
float horizontalRadio = size.width*1.0/width;
float radio = 1;
radio = verticalRadio < horizontalRadio ? horizontalRadio : verticalRadio;
CGRect displayRect = CGRectMake((size.width - width*radio)/2.0f,
(size.height-height*radio)/2.0f,
width*radio,
height*radio);
// create a bitmap context and then set the context to current using
UIGraphicsBeginImageContext(size);
//clip
UIRectClip(displayRect);
//draw the bitmap in rect
[self drawInRect:displayRect];
// from context to get a UIIMage
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// move context out of buffer
UIGraphicsEndImageContext();
NSLog(#"getSubImage ---->");
// return.
return scaledImage;
}

Resources