AutoLayout - Keep Ratio of Image With Horizontal Constraints (Swift Xcode 6)

邮差的信 提交于 2019-12-10 10:36:37

问题


I've been trying to implement a timeline of picture (as instagram or facebook). However, I've been struggling with the ratio of the image.

Here's my xib that contains my Cell :

I want the picture to keep its ratio and to completely fill the width of the cell. I've set 4 autolayout constraint on the UIImageView as 0-0 for horizontal constraint and 5-5 for top/bottom constraints. I've also set the ViewMode to "Aspect Fit".

I've tried different setup :

  1. set the height of UIImageView to a specific value : --> The width of the image is modify to keep the image ratio
  2. don't set the height of UIImageView --> it considers that the height is equal to 0 and therefore doesn't even display the image
  3. set the height greater or equal to a specific value : -- > same behavior as 1. (The width of the image is modify to keep the image ratio)

I'm loading the image from an URL so I've been using the lib Haneke (https://github.com/Haneke/HanekeSwift) with the following function : imageView.hnk_setImageFromURL(url).

It has an automatic resize of the image and I don't know how to get the original width/height of the image to set the height manually.

Again, what I want is the picture to keep its ratio and to completely fill the width of the cell.

Anyone has a suggestion ?

Thanks a lot !


回答1:


This is the setup I came up with. It's a quick and dirty demo, but I would assume you'd want the image to always be centered. You can set the Horizontal and Vertical Center Constraint in storyboard to always keep it centered If you want it to always completely fill the view, you can replace Equal Height with Equal Width, but by doing so, the imageView will run off the screen on some sizes because of the aspect ratio constraint

I've also included screenshots of the view at different sizes



来源:https://stackoverflow.com/questions/27119325/autolayout-keep-ratio-of-image-with-horizontal-constraints-swift-xcode-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!