I need to crop UIImage which is loaded in UIScrollview with some rect of Another UIView which is also in UIScrollView
Following is View Hierarchy
--> View
--> UIScrollView
--> viewBase (UIView)
--> UIImageView -> (Zoomed & rotated )
--> UIView (Target View)(Movable User can move anywhere in scrollview to crop rect)
My Image is Rotated & Zoomed I need to get exact part of image in TargetView
I am drawing UIImage with rotation on context following is code
CGFloat angleCroppedImageRetreacted = atan2f(self.imgVPhoto.transform.b, self.imgVPhoto.transform.a);
angleCroppedImageRetreacted = angleCroppedImageRetreacted * (180 / M_PI);
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.imgVPhoto.image.size.width, self.imgVPhoto.image.size.height)];
rotatedViewBox.transform = CGAffineTransformMakeRotation(-angleCroppedImageRetreacted);
CGSize rotatedSize = rotatedViewBox.frame.size;
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0f, rotatedSize.height / 2.0f);
CGContextRotateCTM(bitmap, -angleCroppedImageRetreacted);
CGContextScaleCTM(bitmap, 1.0f, -1.0f);
CGContextDrawImage(bitmap, CGRectMake(-self.imgVPhoto.image.size.width / 2.0f,
-self.imgVPhoto.image.size.height / 2.0f,
self.imgVPhoto.image.size.width,
self.imgVPhoto.image.size.height),
self.imgVPhoto.image.CGImage);
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
And it works fine . I am getting Rotated UIImage same as i can see in Simulator
For converting Point of Target View to UIImage I use following code which is NOT WORKING
CGPoint imageViewPoint = [self.viewBase convertPoint:self.targetImageview.center toView:self.imgVPhoto];
float percentX = imageViewPoint.x / self.imgVPhoto.frame.size.width;
float percentY = imageViewPoint.y / self.imgVPhoto.frame.size.height;
CGPoint imagePoint = CGPointMake(resultImage.size.width * percentX, resultImage.size.height * percentY);
rect.origin = imagePoint;
//rect.origin.x *= (self.imgVPhoto.image.size.width / self.imgVPhoto.frame.size.width);
//rect.origin.y *= (self.imgVPhoto.image.size.height / self.imgVPhoto.frame.size.height);
imageRef = CGImageCreateWithImageInRect([resultImage CGImage], rect);
img = [UIImage imageWithCGImage:imageRef scale:viewImage.scale orientation:viewImage.imageOrientation];
I think issue is we can't use Rect after Transform Apply
Please Help me to crop UIImage which is zoomed and rotated from rect on same Hierarchy
If you need more info pls ask
I am answering my own question .
Thanks to Matic for giving a idea
I changed a logic
I have achieved same functionality what i looking for
CGPoint locationInImageView = [self.viewBase convertPoint:self.targetImageview.center toView:self.view]; // received from touch
locationInImageView = [self.view convertPoint:locationInImageView toView:self.imgVPhoto];
// I GOT LOCATION IN UIIMAGEVIEW OF TOUCH POINT
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0);
[self.imgVPhoto.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img1 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// I GOT UIIMAGE FROM CURRENT CONTEXT
CGFloat width = self.targetImageview.frame.size.width * self.zoomScale ;
CGFloat height = self.targetImageview.frame.size.height * self.zoomScale ;
//2 IS SCALE FACTOR
CGFloat xPos = (locationInImageView.x * 2) - width / 2;
CGFloat yPos = (locationInImageView.y * 2) - height / 2;
CGRect rect1 = CGRectMake(xPos, yPos, width, height);
CGImageRef imageRef = CGImageCreateWithImageInRect([img1 CGImage], rect1);
// YAHHH YOU HAVE EXACT IMAGE
UIImage *img = [UIImage imageWithCGImage:imageRef scale:img1.scale orientation:img1.imageOrientation];
I develop an application in which i process the image using its pixels but in that image processing it takes a lot of time. Therefore i want to crop UIImage (Only middle part of image i.e. removing/croping bordered part of image).I have the develop code are,
- (NSInteger) processImage1: (UIImage*) image
{
CGFloat width = image.size.width;
CGFloat height = image.size.height;
struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel));
if (pixels != nil)
{
// Create a new bitmap
CGContextRef context = CGBitmapContextCreate(
(void*) pixels,
image.size.width,
image.size.height,
8,
image.size.width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast
);
if (context != NULL)
{
// Draw the image in the bitmap
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage);
NSUInteger numberOfPixels = image.size.width * image.size.height;
NSMutableArray *numberOfPixelsArray = [[[NSMutableArray alloc] initWithCapacity:numberOfPixelsArray] autorelease];
}
How i take(croping outside bordered) the middle part of UIImage?????????
Try something like this:
CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
Note: cropRect is smaller rectangle with middle part of the image...
I was looking for a way to get an arbitrary rectangular crop (ie., sub-image) of a UIImage.
Most of the solutions I tried do not work if the orientation of the image is anything but UIImageOrientationUp.
For example:
http://www.hive05.com/2008/11/crop-an-image-using-the-iphone-sdk/
Typically if you use your iPhone camera, you will have other orientations like UIImageOrientationLeft, and you will not get a correct crop with the above. This is because of the use of CGImageRef/CGContextDrawImage which differ in the coordinate system with respect to UIImage.
The code below uses UI* methods (no CGImageRef), and I have tested this with up/down/left/right oriented images, and it seems to work great.
// get sub image
- (UIImage*) getSubImageFrom: (UIImage*) img WithRect: (CGRect) rect {
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
// translated rectangle for drawing sub image
CGRect drawRect = CGRectMake(-rect.origin.x, -rect.origin.y, img.size.width, img.size.height);
// clip to the bounds of the image context
// not strictly necessary as it will get clipped anyway?
CGContextClipToRect(context, CGRectMake(0, 0, rect.size.width, rect.size.height));
// draw image
[img drawInRect:drawRect];
// grab image
UIImage* subImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return subImage;
}
Because I needed it just now, here is M-V 's code in Swift 4:
func imageWithImage(image: UIImage, croppedTo rect: CGRect) -> UIImage {
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
let drawRect = CGRect(x: -rect.origin.x, y: -rect.origin.y,
width: image.size.width, height: image.size.height)
context?.clip(to: CGRect(x: 0, y: 0,
width: rect.size.width, height: rect.size.height))
image.draw(in: drawRect)
let subImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return subImage!
}
It would ultimately be faster, with a lot less image creation from sprite atlases, if you could set not only the image for a UIImageView, but also the top-left offset to display within that UIImage. Maybe this is possible. It would certainly eliminate a lot of effort!
Meanwhile, I created these useful functions in a utility class that I use in my apps. It creates a UIImage from part of another UIImage, with options to rotate, scale, and flip using standard UIImageOrientation values to specify. The pixel scaling is preserved from the original image.
My app creates a lot of UIImages during initialization, and this necessarily takes time. But some images aren't needed until a certain tab is selected. To give the appearance of quicker load I could create them in a separate thread spawned at startup, then just wait till it's done when that tab is selected.
This code is also posted at Most efficient way to draw part of an image in iOS
+ (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)aperture {
return [ChordCalcController imageByCropping:imageToCrop toRect:aperture withOrientation:UIImageOrientationUp];
}
// Draw a full image into a crop-sized area and offset to produce a cropped, rotated image
+ (UIImage*)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)aperture withOrientation:(UIImageOrientation)orientation {
// convert y coordinate to origin bottom-left
CGFloat orgY = aperture.origin.y + aperture.size.height - imageToCrop.size.height,
orgX = -aperture.origin.x,
scaleX = 1.0,
scaleY = 1.0,
rot = 0.0;
CGSize size;
switch (orientation) {
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
size = CGSizeMake(aperture.size.height, aperture.size.width);
break;
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
size = aperture.size;
break;
default:
assert(NO);
return nil;
}
switch (orientation) {
case UIImageOrientationRight:
rot = 1.0 * M_PI / 2.0;
orgY -= aperture.size.height;
break;
case UIImageOrientationRightMirrored:
rot = 1.0 * M_PI / 2.0;
scaleY = -1.0;
break;
case UIImageOrientationDown:
scaleX = scaleY = -1.0;
orgX -= aperture.size.width;
orgY -= aperture.size.height;
break;
case UIImageOrientationDownMirrored:
orgY -= aperture.size.height;
scaleY = -1.0;
break;
case UIImageOrientationLeft:
rot = 3.0 * M_PI / 2.0;
orgX -= aperture.size.height;
break;
case UIImageOrientationLeftMirrored:
rot = 3.0 * M_PI / 2.0;
orgY -= aperture.size.height;
orgX -= aperture.size.width;
scaleY = -1.0;
break;
case UIImageOrientationUp:
break;
case UIImageOrientationUpMirrored:
orgX -= aperture.size.width;
scaleX = -1.0;
break;
}
// set the draw rect to pan the image to the right spot
CGRect drawRect = CGRectMake(orgX, orgY, imageToCrop.size.width, imageToCrop.size.height);
// create a context for the new image
UIGraphicsBeginImageContextWithOptions(size, NO, imageToCrop.scale);
CGContextRef gc = UIGraphicsGetCurrentContext();
// apply rotation and scaling
CGContextRotateCTM(gc, rot);
CGContextScaleCTM(gc, scaleX, scaleY);
// draw the image to our clipped context using the offset rect
CGContextDrawImage(gc, drawRect, imageToCrop.CGImage);
// pull the image from our cropped context
UIImage *cropped = UIGraphicsGetImageFromCurrentImageContext();
// pop the context to get back to the default
UIGraphicsEndImageContext();
// Note: this is autoreleased
return cropped;
}
#Very small/simple Swift 5 version,
You shouldn't mix UI and CG objects, they sometimes have very different coordinate spaces. This can make you sad.
Note 👉 : self.draw(at:)
#inlinable private prefix func - (right: CGPoint) -> CGPoint
{
return CGPoint(x: -right.x, y: -right.y)
}
extension UIImage
{
public func cropped(to cropRect: CGRect) -> UIImage?
{
let renderer = UIGraphicsImageRenderer(size: cropRect.size)
return renderer.image
{
_ in
self.draw(at: -cropRect.origin)
}
}
}
Using the function
CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
Here's an example code, used for a different purpose but clips ok.
- (UIImage *)aspectFillToSize:(CGSize)size
{
CGFloat imgAspect = self.size.width / self.size.height;
CGFloat sizeAspect = size.width/size.height;
CGSize scaledSize;
if (sizeAspect > imgAspect) { // increase width, crop height
scaledSize = CGSizeMake(size.width, size.width / imgAspect);
} else { // increase height, crop width
scaledSize = CGSizeMake(size.height * imgAspect, size.height);
}
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
[self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
If you want a portrait crop down the center of every photo.
Use #M-V solution, & replace cropRect.
CGFloat height = imageTaken.size.height;
CGFloat width = imageTaken.size.width;
CGFloat newWidth = height * 9 / 16;
CGFloat newX = abs((width - newWidth)) / 2;
CGRect cropRect = CGRectMake(newX,0, newWidth ,height);
I wanted to be able to crop from a region based on an aspect ratio, and scale to a size based on a outer bounding extent. Here is my variation:
import AVFoundation
import ImageIO
class Image {
class func crop(image:UIImage, source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {
let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))
let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)
let scale = max(
targetRect.size.width / sourceRect.size.width,
targetRect.size.height / sourceRect.size.height)
let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
image.drawInRect(drawRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
}
There are a couple things that I found confusing, the separate concerns of cropping and resizing. Cropping is handled with the origin of the rect that you pass to drawInRect, and scaling is handled by the size portion. In my case, I needed to relate the size of the cropping rect on the source, to my output rect of the same aspect ratio. The scale factor is then output / input, and this needs to be applied to the drawRect (passed to drawInRect).
One caveat is that this approach effectively assumes that the image you are drawing is larger than the image context. I have not tested this, but I think you can use this code to handle cropping / zooming, but explicitly defining the scale parameter to be the aforementioned scale parameter. By default, UIKit applies a multiplier based on the screen resolution.
Finally, it should be noted that this UIKit approach is higher level than CoreGraphics / Quartz and Core Image approaches, and seems to handle image orientation issues. It is also worth mentioning that it is pretty fast, second to ImageIO, according to this post here: http://nshipster.com/image-resizing/
I am using the following crop method to crop a uiimage that's sitting in a UIImageView which is then sitting in a UIScrollView.
-(UIImage *)cropImage:(UIImage *)image
{
float scale = 1.0f/_scrollView.zoomScale;
NSLog(#"Oh and heres that zoomScale: %f", _scrollView.zoomScale);
CGRect visibleRect;
visibleRect.origin.x = _scrollView.contentOffset.x * scale;
visibleRect.origin.y = _scrollView.contentOffset.y * scale;
visibleRect.size.width = _scrollView.bounds.size.width * scale;
visibleRect.size.height = _scrollView.bounds.size.height * scale;
NSLog(#"Oh and here's that CGRect: %f", visibleRect.origin.x);
NSLog(#"Oh and here's that CGRect: %f", visibleRect.origin.y);
NSLog(#"Oh and here's that CGRect: %f", visibleRect.size.width);
NSLog(#"Oh and here's that CGRect: %f", visibleRect.size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], visibleRect);
UIImage *croppedImage = [[UIImage alloc] initWithCGImage:imageRef];
CGImageRelease(imageRef);
return croppedImage;
}
I need the image to be cropped to a CGSize of (321,115). Upon cropping the image and seeing the print results, I can see that visibleRect is (0,0,321,115) - what it is supposed to be, the croppedImage UIImage then has width:321 and height:115. for some reason however the image appears to be zoomed in entirely too far (the method cropped a smaller portion of the original image to a size of 321x115).
Why is this method not correctly cropping my image?
-As a side note: When I call this method, I am calling like so _croppedImage = [self cropImage:_imageView.image]; which sets a UIImage property of a custom UIView class to the cropped image.
Please try this function. It may help you.
Parameters:
UIImage
CGSize (321,115) or any size
// crop image - image will crop from full image
- (UIImage *)cropImageWithImage:(UIImage *)image scaledToSize:(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 (image.size.width > image.size.height) {
ratio = newSize.width / image.size.width;
delta = (ratio*image.size.width - ratio*image.size.height);
offset = CGPointMake(delta/2, 0);
}
else {
ratio = newSize.width / image.size.height;
delta = (ratio*image.size.height - ratio*image.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 * image.size.width) + delta,
(ratio * image.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);
[image drawInRect:clipRect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
To crop only selected portion of image
Please check this link
I want to rotate image (arrow) in circular path in coreGraphics like this image. in circular path.
input image:
output after rotation:
This will return rotated image
- (UIImage *)rotateImage:(UIImage *)image onDegrees:(float)degrees
{
CGFloat rads = M_PI * degrees / 180;
float newSide = MAX([image size].width, [image size].height);
CGSize size = CGSizeMake(image.size.width, newSide);
UIGraphicsBeginImageContext(size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, image.size.width, newSide/2);
CGContextRotateCTM(ctx, rads);
CGRect r = CGRectMake(0,-[image size].height/2,image.size.width,image. size.height);
[image drawInRect:r];
UIImage *i = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return i;
}
UIImage *arrowRotated180 = [self rotateImage:[UIImage imageNamed:#"arrowImage"] onDegrees:180];
UIImage *arrowRotated90 = [self rotateImage:[UIImage imageNamed:#"arrowImage"] onDegrees:90];
Put three images and rotate 2 & 3 image as follow.
imageview2.transform = CGAffineTransformMakeRotation(M_PI/4);
imageview3.transform = CGAffineTransformMakeRotation(M_PI/2);
Hope this will help you...
try UIcollectionview it worked my case .
I've got the following function, previous to iOS 7 & XCode 5 it worked as expected. The function takes an image and a cropSize. The image is the one to be cropped to a specified size, which is defined by CGSize cropSize. The purpose of the function is to crop the image to a certain size and then return the cropped image.
- (UIImage *) cropImage:(UIImage *)originalImage cropSize:(CGSize)cropSize
{
//calculate scale factor to go between cropframe and original image
float SF = originalImage.size.width / cropSize.width;
//find the centre x,y coordinates of image
float centreX = originalImage.size.width / 2;
float centreY = originalImage.size.height / 2;
//calculate crop parameters
float cropX = centreX - ((cropSize.width / 2) * SF);
float cropY = centreY - ((cropSize.height / 2) * SF);
CGRect cropRect = CGRectMake(cropX, cropY, (cropSize.width *SF), (cropSize.height * SF));
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
//keep orientation if landscape
UIImage *newImage;
if (originalImage.size.width > originalImage.size.height || originalImage.size.width == originalImage.size.height) {
newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];
}
else
{
newImage = [UIImage imageWithCGImage:imageRef];
}
CGImageRelease(imageRef);
//Now want to scale down cropped image!
//want to multiply frames by 2 to get retina resolution
CGRect scaledImgRect = CGRectMake(0, 0, (cropSize.width * 2), (cropSize.height * 2));
UIGraphicsBeginImageContextWithOptions(scaledImgRect.size, NO, [UIScreen mainScreen].scale);
[newImage drawInRect:scaledImgRect];
UIImage *scaledNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledNewImage;
}
The problem is that it all works fine in with a UIImage that is passed in that is in landscape orientation, the image is cropped as expected, however if the image passed in was taken in portrait, then the resulting image (the cropped result in scaledNewImage) is rotated 90 degrees on its side, which I don't want.
It is as if the portrait image is being worked on as if it's in landscape - and so the function cropped what should be a portrait orientated image in landscape instead of portrait.
This isn't so apparent if the crop area is square, however if the area to be cropped is a landscape rectangle then it's cropping it along the length of the portrait rather than the width. Hope I'm making sense!
This issue didn't occur prior to iOS 7 & XCode 5.. so I'm not sure exactly what's changed. Any help appreciated, thanks.
Solved this issue with the help of an answer here: https://stackoverflow.com/a/14712184/521653
- (UIImage *) cropImage:(UIImage *)originalImage cropSize:(CGSize)cropSize
{
NSLog(#"original image orientation:%d",originalImage.imageOrientation);
//calculate scale factor to go between cropframe and original image
float SF = originalImage.size.width / cropSize.width;
//find the centre x,y coordinates of image
float centreX = originalImage.size.width / 2;
float centreY = originalImage.size.height / 2;
//calculate crop parameters
float cropX = centreX - ((cropSize.width / 2) * SF);
float cropY = centreY - ((cropSize.height / 2) * SF);
CGRect cropRect = CGRectMake(cropX, cropY, (cropSize.width *SF), (cropSize.height * SF));
CGAffineTransform rectTransform;
switch (originalImage.imageOrientation)
{
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(M_PI_2), 0, -originalImage.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(-M_PI_2), -originalImage.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(-M_PI), -originalImage.size.width, -originalImage.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
rectTransform = CGAffineTransformScale(rectTransform, originalImage.scale, originalImage.scale);
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], CGRectApplyAffineTransform(cropRect, rectTransform));
UIImage *result = [UIImage imageWithCGImage:imageRef scale:originalImage.scale orientation:originalImage.imageOrientation];
CGImageRelease(imageRef);
//return result;
//Now want to scale down cropped image!
//want to multiply frames by 2 to get retina resolution
CGRect scaledImgRect = CGRectMake(0, 0, (cropSize.width * 2), (cropSize.height * 2));
UIGraphicsBeginImageContextWithOptions(scaledImgRect.size, NO, [UIScreen mainScreen].scale);
[result drawInRect:scaledImgRect];
UIImage *scaledNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledNewImage;
}
That's the updated method there. I implemented the code from the answer linked into my method and it solves the issues. Strange that I didn't have these before iOS 7!