Crop and save visible region of UIImageView using

2019-08-09 16:06发布

问题:

I have a fullscreen UIImageView with a image in it set to AspectFill (full bleed), how can I save only the visible portion of the image when its using the Aspect Fill content mode?

CGRect visibleRect;   
visibleRect.size= mImageView.frame.size;
CGImageRef cropped_img = CGImageCreateWithImageInRect(mImageView.image.CGImage, visibleRect);
UIImage *finalImage = [[UIImage alloc]initWithCGImage:cropped_img];
UIImageWriteToSavedPhotosAlbum(finalImage, nil, nil, nil);

This is my current code, cropping and saving works, its just not cropping correctly. Any ideas?

回答1:

Try this:

UIGraphicsBeginImageContext(mImageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef image = CGBitmapContextCreateImage(context);
width = CGImageGetWidth(image);
height = CGImageGetHeight(image);
CGImageRef cropped_img = CGImageCreateWithImageInRect(image, CGRectMake(0, 0, width, height));

// save...

CGImageRelease(image);
UIGraphicsEndImageContext();