JozackOverFlow
JozackOverFlow

Reputation: 267

Fit image in UIImageView using UIViewContentModeScaleAspectFit

I'm facing a really weird problem with UIImageView, I was trying to set an image - which created by take the screenshot of the current view - to an ImageView with content mode is UIViewContentModeScaleAspectFit.

It worked fine when I set the image by the interface builder in the xib file or when I set the image created by [UIImage imageNamed:]. They both worked fine with UIViewContentModeScaleAspectFit.

But when I take the snap shot of a view and set the image to the image view, the image did not fit to the UIImageView. I've tried all the solutions I found on here like .ClipsToBound = YES but they didn't work at all. I'm really confused by now.

Here's the code when I take the screen shot and create the UIImage:

- (UIImage *)screenshotWithRect:(CGRect)captureRect
{
    CGFloat scale = [[UIScreen mainScreen] scale];
    UIImage *screenshot;

    UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, scale);
    CGContextClipToRect (UIGraphicsGetCurrentContext(),captureRect);
    {
        if(UIGraphicsGetCurrentContext() == nil)
        {
            NSLog(@"UIGraphicsGetCurrentContext is nil. You may have a UIView (%@) with no really frame (%@)", [self class], NSStringFromCGRect(self.frame));
        }
        else
        {
            [self.layer renderInContext:UIGraphicsGetCurrentContext()];

            screenshot = UIGraphicsGetImageFromCurrentImageContext();
        }
    }
    UIGraphicsEndImageContext();

    return screenshot;
}

And when I set the image to the image view

UIImage* snap = [[UIImage alloc] init];
// start snap shot
UIView* superView = [self.view superview];
CGRect cutRect = [superView convertRect:self.cutView.frame fromView:_viewToCut];
snap = [superView screenshotWithRect:cutRect];
[self.view addSubview:self.editCutFrameView];
// end snap shot -> show edit view
[self.editCutFrameView setImage:snap];

Here's a picture compare the 2 results: enter image description here

Many thanks for your help.

UPDATE: As @Saheb Roy mentioned about the size, I checked the image size and it's about 400x500px and the thumbnail.png's size is 512x512px so I think it's not about the size of the image.

Upvotes: 0

Views: 227

Answers (1)

Saheb Roy
Saheb Roy

Reputation: 5967

This is because in the second case, the snapshot image is itself exactly that size as you can see. Hence the image is not being stretched or fitted accordingly. Earlier images are fitting to screen accordingly as the images were bigger than the imageview but with different ratio or same than that of the image.

But the one where it is not fitting to the imageview, the image itself is of that much size, i.e. smaller than that of the imageview, hence it is NOT being fitted to the bounds.

Upvotes: 0

Related Questions