How to crop Image using rectangle? - iphone

I am trying to crop an image using this rectangle.But Not getting how to stretch the rectangle.I am having one UIView that is outside and within that other view shown with black border. When I stretch DO i need to change the frame for both UIViews ??
should use Pinchgesture to stretch the rectangle or any other method??
Here four blue handlers are UIView s. How will i determine the dragging of them??
If there please suggest.

Following code for the selecting the box and cropping the image.
-(IBAction) cropImage:(id) sender{
// Create rectangle that represents a cropped image
// from the middle of the existing image
float xCo,yCo;
float width=bottomCornerPoint.x-topCornerPoint.x;
float height=bottomCornerPoint.y-topCornerPoint.y;
if(width<0)
width=-width;
if(height<0)
height=-height;
if(topCornerPoint.x <bottomCornerPoint.x)
{
xCo=topCornerPoint.x;
}
else
{
xCo=bottomCornerPoint.x;
}
if(topCornerPoint.y <bottomCornerPoint.y)
{
yCo=topCornerPoint.y;
}
else {
yCo=bottomCornerPoint.y;
}
CGRect rect = CGRectMake(xCo,yCo,width,height);
// Create bitmap image from original image data,
// using rectangle to specify desired crop area
UIImage *image = [UIImage imageNamed:#"abc.png"];
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// Create and show the new image from bitmap data
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(110, 600, width, height)];
imageView.image=img;
[[self view] addSubview:imageView];
[imageView release];
}
Hope this may helping to lot

Related

Crop Landscape Image Dynamically

I want to crop Image according to red View . There are some points to keep in mind.
1.Image can be scrolled and Zoomed.
2.Red ImageView is created Dynamically according to Image
UIImage* whole = [UIImage imageNamed:#"9.png"]; //I uses this image
CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, incX, incY));
UIImage* part = [UIImage imageWithCGImage:cgImg];
I just want to know How to find the Values of
x, y, incX, incY
Thanks...
Scenario 1: Normal (Not Scrolled)
Expected Result (Ignore Black Border On Top and Bottom)
Scenario 2:Scrolled
Expected Result (Ignore Black Border On Top and Bottom)
Scenario 3: Zoomed
And same Expected Result for the Zoomed One.
In all cases I want the respective Images Inside the Red Rectangle.
For all These I am Using this Code...
-(void)cropClicked:(UIButton*)sender
{
float zoomScale = 1.0 / [mainScrollView zoomScale];
CGRect rect;
rect.size.width = [redImageView bounds].size.width * zoomScale ;
rect.size.height = [redImageView bounds].size.height * zoomScale ;
rect.origin.x = ([mainScrollView bounds].origin.x + redImageView.frame.origin.x );
rect.origin.y = ([mainScrollView bounds].origin.y + redImageView.frame.origin.y );
CGImageRef cr = CGImageCreateWithImageInRect([[mainImageView image] CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:cr];
mainImageView.image=cropped;
UIImageWriteToSavedPhotosAlbum(cropped, nil, nil, nil);
CGImageRelease(cr);
}
Well, as #HDdeveloper rightly said, you can use CGImageCreateWithImageInRect. This take 2 params, the first is the whole image, the second is the frame that you want to crop (so probably the frame of your red imageView).
The problem is that if you're targeting for both retina/non retina; if your whole image is an image #2x and you want to crop the image with the red imageview frame you have to double your frame to get the right screenshot.
So you can try with this method:
//Define the screen type:
#define isRetinaDisplay [[UIScreen mainScreen] respondsToSelector:#selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0)
- (UIImage*)cropInnerImage:(CGRect)rect {
//Take a screenshot of the whole image
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* ret = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rct;
//Double the frame if you're in retina display
if (isRetinaDisplay) {
rct=CGRectMake(rect.frame.origin.x*2, rect.frame.origin.y*2, rect.size.width*2, rect.size.height*2);
} else {
rct=rect;
}
//Crop the image from the screenshot
CGImageRef imageRef = CGImageCreateWithImageInRect([ret CGImage], rct);
UIImage *result = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
//Save and open the result images with Preview.app
[UIImagePNGRepresentation(result) writeToFile: #"/tmp/testCrop.png" atomically: YES];
system("open /tmp/testCrop.png");
[UIImagePNGRepresentation(ret) writeToFile: #"/tmp/testRet.png" atomically: YES];
system("open /tmp/testRet.png");
//
return result;
}
Where the rect parameter must be your red image frame, and self.view.frame must be the equal to the wholeImageView.frame. You can skip the last 4 lines, these are just to see in your Mac what you're cropping.
PS: i use this method to crop an image and set it as background of UIView, this is the reason i have to double the frame.
You can use CGImageRef
pass your rect in the whole image. Then call this on button click
UIImage* whole = [UIImage imageNamed:#"9.png"]; //I uses this image
CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, incX, incY));
UIImage* part = [UIImage imageWithCGImage:cgImg];

Rotate UIImage: can't make it work

This is part of a big project, but my problem can be simplified as:
I have a simple view with an ImageView and a "Rotate" button. Whenever I press the button, the image inside the ImageView will rotate 90 degree. From much of what I've found on StackOverflow and other sites, this should work (please note that my image is a square image, which has width and height equal to 464):
- (UIImage *) getRotatedImageFromImage:(UIImage*)image:(int)rotate_index
{
UIImage *rotatedImage;
// Get image width, height of the bounding rectangle
CGRect boundingRect = CGRectMake(0, 0, image.size.width, image.size.height);
NSLog(#"width = %f, height = %f",boundingRect.size.width,boundingRect.size.height);
NSLog(#"rotate index = %d",rotate_index);
// Create a graphics context the size of the bounding rectangle
UIGraphicsBeginImageContext(boundingRect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRotateCTM(context, rotate_index*M_PI/2);
// Draw the image into the context
[image drawInRect:boundingRect];
// Get an image from the context
rotatedImage = UIGraphicsGetImageFromCurrentImageContext();
// Clean up
UIGraphicsEndImageContext();
NSLog(#"rotatedImage size = (%f, %f)",rotatedImage.size.width,rotatedImage.size.height);
return rotatedImage;
}
- (IBAction) rotateImage
{
NSLog(#"rotate image");
rotateIndex++;
if (rotateIndex >= 4)
rotateIndex = 0;
[imageView setImage: [self getRotatedImageFromImage:imageToSubmit :rotateIndex]];
}
But it doesn't work for some reasons. What I have is: when pressing the button, the image only appears when rotateIndex gets to 0, and the image is the same as the original image (which is expected). When rotateIndex is 1, 2, 3, the imageView displays nothing, even though the size of rotatedImage printed out is correct (i.e. 464 x 464) .
Could anyone tell me what's going wrong?
Thanks.
//create rect
UIImageView *myImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"image.png"]];
//set point of rotation
myImageView.center = CGPointMake(100.0,100.0);
//rotate rect
myImageView.transform =CGAffineTransformMakeRotation(3.14159265/2); //rotation in radians
I was able to solve my problem. Here is my solution, using CGImageRef and [UIImage imageWithCGImage: scale: orientation:]
CGImageRef cgImageRef = CGBitmapContextCreateImage(context);
UIImageOrientation imageOrientation;
switch (rotate_index) {
case 0: imageOrientation = UIImageOrientationUp; break;
case 1: imageOrientation = UIImageOrientationLeft; break;
//2 more cases for rotate_index = 2 and 3
}
rotatedImage = [UIImage imageWithCGImage:cgImageRef scale:1.0 orientation:imageOrientation];`

Erase a rect of an UIImageView

I want to know, how can I erase a custom rect (with, for example, an UIView in IB or something else) of an UIImageView in order to display an other UIImageView positioned underneath.
I didn't manage to do it using some response in the forum...
This will clear a rect in an image:
- (UIImage *)clearRect:(CGRect)rect inImage:(UIImage *)image {
if (UIGraphicsBeginImageContextWithOptions != NULL)
UIGraphicsBeginImageContextWithOptions([image size], NO, 0.0);
else
UIGraphicsBeginImageContext([image size]);
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:CGRectMake(0.0, 0.0, [image size].width, [image size].height)];
CGContextClearRect(context, rect);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;
}
Just load your image and clear the rects before assigning it to the image view:
UIImage *image = [UIImage imageNamed:#"Image.png"];
UIImage *maskedImage = [self clearRect:CGRectMake(10.0, 10.0, 50.0, 50.0) inImage:image];
[imageView setImage:maskedImage];
probably not the best solution but you can do the other way and take the 4 parts around the rect separately and combine them afterwards without the inner rect. You would repeat this as long as you have rect's to crop out.
You cannot clear the UIImageView itself because this just draws the UIImage. So you have erase the rect in the UIImage. Create a bitmap context, draw the image into it. Erase the part you want to "see through" with CGContextClearRect. When create a new new image from the bitmap context.

how to crop some portion of scaled, rotated image-view

I am unable to crop he image from image view, which is scaled and rotated before cropping. used existing cropping methods.but its applicable only for image-view which is fixed.Hope code will helpful.
Finally succeeded cropping rotated scaled image.
1) Need to crop the entire scaled or rotated image.
2)crop the rect from cropped Image. you will get final scaled or rotated cropped image.
Im posting sample code , it may helpful for others.
UIGraphicsBeginImageContextWithOptions(self.view.frame.size, NO, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGRect rect = CGRectMake(100,100 ,200, 200);//Rect we need from scaled or rotated image.
CGImageRef cropped = CGImageCreateWithImageInRect(viewImage.CGImage, rect);
UIImage *img = [UIImage imageWithCGImage:cropped];
CGImageRelease(cropped);
Thanks.
Try This(if you need to crop the corners):
UIImageView *imageSubview = [[UIImageView alloc] initWithFrame:CGRectMake(50.0f, 5.0f,80.0f, 60.0f)];
[imageSubview setImage:actualImage];
[imageSubview setContentMode:UIViewContentModeScaleToFill];
[imageSubview.layer setCornerRadius:10.0];
[imageSubview.layer setMasksToBounds:YES];
[cell addSubview:imageSubview];
Just increase the radius and you will make it circle, or walk on this path you'll get your actual solution.:)
UIImage *myImage = [UIImage imageNamed:#"photo.png"];
CGRect cropRect = CGRectMake(0.0, 0.0, 320.0, 44.0));
CGImageRef croppedImage = CGImageCreateWithImageInRect([myImage CGImage], cropRect);
UIImageView *myImageView = [[UIImageView alloc] initWithFrame:cropRect];
[myImageView setImage:[UIImage imageWithCGImage:croppedImage]];
CGImageRelease(croppedImage);
its for cropping particular height and width

How to create an image from a UIView / UIScrollView

I have an image in an UIScrollView, that can be scrolled and zoomed.
When the user presses a button, I want the code to create an image from whatever part of the UIScrollView is inside an area I specify with a CGRect.
I've seen code to crop UIImages, but I can't adapt it to do the same for a view, because it uses CGContextDrawImage.
Any thoughts?
Cheers,
Andre
I've managed to get it.
Here's my solution, based on a few different ones from the web:
- (UIImage *)imageByCropping:(UIScrollView *)imageToCrop toRect:(CGRect)rect
{
CGSize pageSize = rect.size;
UIGraphicsBeginImageContext(pageSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(resizedContext, -imageToCrop.contentOffset.x, -imageToCrop.contentOffset.y);
[imageToCrop.layer renderInContext:resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
which you call by using:
CGRect clippedRect = CGRectMake(0, 0, 320, 300);
picture.image = [self imageByCropping:myScrollView toRect:clippedRect];