简体   繁体   中英

adjusting the width of UIImageView proportionally when changing height

I have the following code:

UIImageView * imgView = [[UIImageView alloc] initWithImage:image];

NSLog(@"IMAGE SIZE WIDTH IS %f AND HEIGHT IS %f", imgView.frame.size.width, imgView.frame.size.height);

[imgView setUserInteractionEnabled:YES];
[imgView setContentMode:UIViewContentModeScaleAspectFit];

CGRect frame = imgView.frame;
frame.size.width = SCREEN_WIDTH_PORTRAIT;
[imgView setFrame: frame];

however, the height of this view did not change accordingly, what is wrong?

You're telling the view's content to scale, not the view itself. You will have to set both the width and the height to do that.

If you're just trying to scale with orientation changes, though, you could use the UIViewAutoresizingMask and set it like this:

imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth| UIViewAutoresizingFlexibleHeight;

That will make it stretch when switching orientations automatically.

Edit: Here's how you would change the height and maintain the ratio, and animate to the new frame:

CGRect frame = imgView.frame;
float ratio = frame.size.width/SCREEN_WIDTH_PORTRAIT;
frame.size.width = SCREEN_WIDTH_PORTRAIT;
frame.size.height *= ratio;
[UIView animateWithDuration:.25 animations:^{
    [imgView setFrame: frame];              
}];

The image will fit to the frame with the same height as you are only changing the width. So, depending on the aspect ratio of the image, the image may not change it's size. You could determine the aspect ratio of the UIImage and then calculate the height from that with the new width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM