Recently, I had a similar problem, I got a solution using the relative idea (Xa, b = Xa, c - Xb, c)
-(IBAction)crop:(id)sender{ // F = frame // i = image // iv = imageview // sv = self.view // of = offset //Frame Image in imageView coordinates CGRect Fi_iv = [self frameForImage:self.image inImageViewAspectFit:self.imageView]; //Frame ImageView in self.view coordinates CGRect Fiv_sv = self.imageView.frame; //Frame Image in self.view coordinates CGRect Fi_sv = CGRectMake(Fi_iv.origin.x + Fiv_sv.origin.x ,Fi_iv.origin.y + Fiv_sv.origin.y, Fi_iv.size.width, Fi_iv.size.height); //ScrollView offset CGPoint offset = self.scrollView.contentOffset; //Frame Image in offset coordinates CGRect Fi_of = CGRectMake(Fi_sv.origin.x - offset.x, Fi_sv.origin.y - offset.y, Fi_sv.size.width, Fi_sv.size.height); CGFloat scale = self.imageView.image.size.width/Fi_of.size.width; //the crop frame in image offset coordinates CGRect Fcrop_iof = CGRectMake((self.cropView.frame.origin.x - Fi_of.origin.x)*scale, (self.cropView.frame.origin.y - Fi_of.origin.y)*scale, self.cropView.frame.size.width*scale, self.cropView.frame.size.height*scale); UIImage *image = [self image:self.imageView.image cropRect:Fcrop_iof]; // Use this crop image...
You can crop the image using:
//Use this code to crop when you have the right frame -(UIImage*)image:(UIImage *)image cropRect:(CGRect)frame { // Create a new UIImage CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, frame); UIImage *croppedImage = [UIImage imageWithCGImage:imageRef]; CGImageRelease(imageRef); return croppedImage; }
Since you are using ImageView in Aspect Fit, you need to calculate the frame of the image inside the imageView
-(CGRect)frameForImage:(UIImage*)image inImageViewAspectFit:(UIImageView*)imageView { float imageRatio = image.size.width / image.size.height; float viewRatio = imageView.frame.size.width / imageView.frame.size.height; if(imageRatio < viewRatio) { float scale = imageView.frame.size.height / image.size.height; float width = scale * image.size.width; float topLeftX = (imageView.frame.size.width - width) * 0.5; return CGRectMake(topLeftX, 0, width, imageView.frame.size.height); } else { float scale = imageView.frame.size.width / image.size.width; float height = scale * image.size.height; float topLeftY = (imageView.frame.size.height - height) * 0.5; return CGRectMake(0, topLeftY, imageView.frame.size.width, height); } }
I hope this code can work for you as it worked for me.
Best
Raphael.
rcmcastro
source share