简体   繁体   English

更改高度时按比例调整UIImageView的宽度

[英]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: 但是,如果您只是尝试通过方向更改进行缩放,则可以使用UIViewAutoresizingMask并进行如下设置:

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. 您可以确定UIImage的宽高比,然后根据新宽度计算高度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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