问题
In my application the requirement is to grab image from the photo library or camera and if user wants to crop the image then he should be able to do it but I do not have any idea how to crop the image fetched from camera or photo library.
if you have any idea then share it...
回答1:
You can crop your image by using UIGraphicsGetImageFromCurrentImageContext
The idea is to draw your image to a cropped graphic context using CoreGraphics and then exporting the current context to an image.
UIGraphicsGetImageFromCurrentImageContext Returns an image based on the contents of the current bitmap-based graphics context.
Return A image object containing the contents of the current bitmap graphics context.
Try something like that :
- (UIImage*)imageCrop:(UIImage *)imageToCrop toRect:(CGRect)rect
{
UIGraphicsBeginImageContext(rect.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGRect clippedRect = CGRectMake(0, 0, rect.size.width, rect.size.height);
CGContextClipToRect( currentContext, clippedRect);
CGRect drawRect = CGRectMake(rect.origin.x, rect.origin.y, imageToCrop.size.width, imageToCrop.size.height);
CGContextDrawImage(currentContext, drawRect, imageToCrop.CGImage);
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return cropped;
}
hope this helps, Vincent
回答2:
I have done the same thing in Mac, probably you could try that out,
+(NSImage *)BreakImageForFirstImage:(NSImage *)pSrcImage Size:(NSSize)imageSize{
/*
Create a new NSImage with the size of the subrect, lock focus on it, draw the sub rect of the source image into
the new, locked image using -drawInRect:fromRect:operation:fraction: ("fromRect:" should be the subrect of the
source; the first rect argument will be a rect of the same size as the subrect, with a 0,0 origin), then unlock
focus from the new image. Done. Because of all that's involved in this, it might still be more efficient just to
load individual images
*/
NSSize srcSize = [pSrcImage size];
int subImageHeight = imageSize.height;
int subImageWidth = imageSize.width;
NSRect subImageRect = NSMakeRect(0,0,imageSize.width,imageSize.height);
NSRect tempRect = NSMakeRect(0,0,imageSize.width,imageSize.height);
//NSMutableArray *pImageArray = [[NSMutableArray alloc]initWithCapacity:noOfImages];
NSImage *pTempImage = nil;
int rowId =0;
int colId = 0;
//for(;rowId<noOfRow;rowId++)
{
pTempImage = [[NSImage alloc]initWithSize:imageSize];
tempRect = NSMakeRect(rowId*subImageWidth,colId*subImageHeight,subImageWidth,subImageHeight);
[pTempImage lockFocus];
[pSrcImage drawInRect:subImageRect fromRect:tempRect operation:NSCompositeSourceOver fraction:1.0];
[pTempImage unlockFocus];
//[pImageArray insertObject:pTempImage atIndex:rowId];
}
return pTempImage;
/* */
}
May be at some places , you might need to convert NS to UI to make it run for iOS
来源:https://stackoverflow.com/questions/9578821/iphonehow-to-crop-image-in-ios5