How to crop zoomed image in xcode?

2020-05-03 01:26发布

问题:

I have done zooming of an image. now I want to crop that zoomed image.
Is it possible to do that??
I used below code for zooming an image.

//Scroll View settings for Zoomin-ZoomOut
Scroll.contentSize= CGSizeMake(img.frame.size.width, img.frame.size.height);
Scroll.maximumZoomScale=3.0;
Scroll.minimumZoomScale=.20;
Scroll.clipsToBounds=YES;
Scroll.delegate=self;
[Scroll addSubview:img];
Scroll.imageContainer=img;


- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{       
    return img; 
}

Here I have used customScroll Class.

回答1:

If you are zooming an image in scroll view and wanna crop visible area try this:

-(IBAction) cropSelecteArea
{
//Calculate the required area from the scrollview
CGRect visibleRect;
float scale = 1.0f/scrollView.zoomScale;
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;
UIImage *image = [self imageByCropping:previewImage toRect:visibleRect];
//UIImage *image = imageFromView(imageView.image, &visibleRect);
[croppedImageImageView setImage:self.objPostPikUploadPhotoPage.croppedImage];
}


- (UIImage*)imageByCropping:(UIImage *)myImage toRect:(CGRect)cropToArea{
CGImageRef cropImageRef = CGImageCreateWithImageInRect(myImage.CGImage, cropToArea);
UIImage* cropped = [UIImage imageWithCGImage:cropImageRef];

CGImageRelease(cropImageRef);
return cropped;
}