缩放的UIImageView,以适应宽度与自动版式 [英] Scaling UIImageView to fit width with AutoLayout

查看:618
本文介绍了缩放的UIImageView,以适应宽度与自动版式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UIScrollView的顶部一个UIImageView,我想以适合装置宽度,其高度然后被自动设置,使得图像比为preserved

I have a UIImageView on top of a UIScrollView, and I would like it to fit the device width, its height then being automatically set so that the image ratio is preserved.

我使用的自动布局,所以我用约束到的UIImageView顶端绑定,左和屏幕的右边缘。
我的问题是,在UIImageView的自动调整其框架以适应UIImage的高度。而且我真的不能改变这个框架之后,因为它允许的UIImageView和其他UI元素之间的差距,这应该是刚下了。

I am using Auto Layout, so I used constraints to bind the UIImageView to the top, left and right edges of the screen. My problem is, the UIImageView automatically resizes its frame to fit the UIImage height. And I cannot really change this frame afterwards, as it lets a gap between the UIImageView and the other UI elements, that are supposed to be just under it.

我发现它放入了的UIImageView之前手动调整图像以良好的尺寸一种解决方法,但它不是非常有效,而且当视图大小,例如创建问题,设备旋转时。

I found a workaround by manually resizing the image to the good size before putting it into the UIImageView, but it isn't very efficient, and it creates problem when the view is resized, for example when the device rotates.

有没有人找到了一种方法来强制的UIImageView来改变它的框架,并保持它,而不是使用图像的大小?

Has anyone found a way to force the UIImageView to change its frame and to keep it rather than using the image's size ?

皮埃尔

编辑:我加了截图,所以你可以看到这个问题。

EDIT : I added screenshots so you can see the problem.

这是预期的结果:

推荐答案

好吧,我找到一个合适的解决我的问题。

OK, I found a suitable solution to my problem.

我估计我要为我的图片这样的正确的高度:

I calculate the correct height that I want for my picture like this :

correctedHeight =屏幕宽度/宽*高

correctedHeight = screenWidth / width * height

在那之后,我以编程方式updateViewConstraints方法中添加一个高度约束。

After that, I add a height constraint programmatically in the updateViewConstraints method.

我用这个code:

[imageView addConstraint:[NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant: correctImageViewHeight]];

两件事情想后:


  • 每次调用此方法时去除约束(否则你最终与冲突的约束)。要做到这一点,我使用 [ImageView的removeConstraint:imageView.constraints.lastObject];

  • [超级updateViewConstraints]; 方法内。如果你忘了,它崩溃。

  • removing the constraint each time this method is called (otherwise you end up with conflicting constraints). To achieve this, I use [imageView removeConstraint: imageView.constraints.lastObject] ;
  • putting[super updateViewConstraints] ; inside the method. If you forget, it crashes.

我没有这么做过,但我可以很容易地看到我怎么可以更新我的correctHeight变量时,该设备旋转。

I haven't done it yet, but I can easily see how I could update my correctHeight variable when the device rotates.

这篇关于缩放的UIImageView,以适应宽度与自动版式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆