How do I capture a zoomed UIImageView inside of a Scrollview to crop?

人盡茶涼 提交于 2019-11-30 10:39:58
UIImage* imageFromView(UIImage* srcImage, CGRect* rect)
{
    CGImageRef cr = CGImageCreateWithImageInRect(srcImage.CGImage, *rect);
    UIImage* cropped = [UIImage imageWithCGImage:cr];

    CGImageRelease(cr);
    return cropped;
}
-(void) doneEditing
{
    //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;


    FinalOutputView* outputView = [[FinalOutputView alloc] initWithNibName:@"FinalOutputView" bundle:[NSBundle mainBundle]];
    outputView.image = imageFromView(imageView.image, &visibleRect);

    [self.navigationController pushViewController:outputView animated:YES];
    [outputView release];
}

Loading Orginal Image:

Zooming Image:

Finally Capturing the Image

If you want to take screenshot from the whole view of scrollView (after zooming) you can do this:

UIImage* image = nil;
UIGraphicsBeginImageContext(self.scrollView.contentSize);
{
    //save previous frames
    CGPoint savedContentOffset = self.scrollView.contentOffset;
    CGRect savedFrame = self.scrollView.frame;
    CGRect imgFrame  = self.imageView.frame;

    //set the frames with current content size
    self.scrollView.contentOffset = CGPointZero;
    self.scrollView.frame = CGRectMake(0, 0, self.scrollView.contentSize.width, self.scrollView.contentSize.height);
    self.imageView.frame = self.scrollView.frame;

    //render image now :)
    [self.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
    image = UIGraphicsGetImageFromCurrentImageContext();

    //now set the frames again with old ones :)
    self.scrollView.contentOffset = savedContentOffset;
    self.scrollView.frame = savedFrame;
    self.imageView.frame = imgFrame;
    [self viewForZoomingInScrollView:self.scrollView];
}
UIGraphicsEndImageContext();

//get the documents path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//save file as savedImage.png
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];

//get the png data from image
NSData *imageData = UIImagePNGRepresentation(image);
//write it now
[imageData writeToFile:savedImagePath atomically:NO];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!