Adam G
Adam G

Reputation: 1188

Objective C - Set ImageView Width and Maintain Aspect Ratio

I am using the following animation to show a full screen image of a thumbnail onto the view:

[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

            [testImageView setFrame:CGRectMake(0, 0, testImage.size.width, testImage.size.height)];

        }completion:^(BOOL finished){

}];

However, this will not contain the image within the bounds of the screen if it is a large image.

Is there a way that I can set the width of the image to the width of the screen, and adjust the image's height then to keep the proper aspect ratio?

Upvotes: 0

Views: 3936

Answers (3)

jithin
jithin

Reputation: 489

Please try this below code:

testImageView 
    =[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y ,self.view.frame.size.width, self.view.frame.size.height
    )]

Upvotes: 0

MatthewLuiHK
MatthewLuiHK

Reputation: 701

Like the above method but with a bit more modification:

CGFloat verticalScale = image.height / bounds.height;
CGFloat horizontalScale = image.width / bounds.width;
CGFloat scale = max(verticalScale,horizontalScale);
CGFloat imageViewHeight = image.height / scale;
CGFloat imageViewWidth = image.width / scale;
CGRect imageViewFrame = CGRectMake(x: DESIRE_X, y: DESIRE_Y, width:imageViewWidth ,height:imageViewHeight)
imageView.frame = imageViewFrame;
imageView.contentMode = UIViewContentModeScaleAspectFill;

Upvotes: 1

John
John

Reputation: 535

CGRect bounds = [UIScreen mainScreen].bounds;
[testImageView setFrame:bounds];
testImageView.contentMode = UIViewContentModeScaleAspectFit;

But there may be some paddings if the image's scale is not equal to screen's.If you prefer the image to cover the full screen, then change contentMode to UIViewContentModeScaleAspectFill.

Upvotes: 1

Related Questions