故事板和自动布局:如何制作圆形图像
在故事板(xcode 6)我想要一个从Facebook的循环用户图像configuration文件。
所以我使用自动布局在故事板上创build了这个界面:
然后,使用Facebook iOS sdk我采取用户configuration文件(使用swift):
var facebookProfileUrl = "http://graph.facebook.com/\(userId!)/picture?type=normal";
在故事板中,我将图像设置为“适合缩放”模式。 要使图像视图循环使用下面的代码:
self.facebookProfileImage.layer.cornerRadius = self.facebookProfileImage.frame.size.width / 2; self.facebookProfileImage.clipsToBounds = true;
当我运行代码时,无论如何,图像看起来不是循环的:
我想这个问题是自动布局,但我不知道。 我怎样才能使图像完美的圆形?
两个步骤:
- 通过在UIImageView中添加一个“Horizontal Center In Container”约束(编辑器>alignment>容器中的水平居中)来居中放置UIImageView。
- 删除当前在UIImageView上设置的前后约束。
为什么? UIImageView正在拉伸,因为自动布局需要考虑您在UIImageView上设置的前后约束。 为了certificate我的观点,将前后约束的优先级设置为小于高度和宽度约束的优先级。 你应该看到像你期望的圆形图像,但它可能不会居中。
我刚刚做了同样的事情,这对我有用
self.imageView.image = [ImageHelper getImage]; //retrieve image self.imageView.layer.cornerRadius = self.imageView.frame.size.height / 2; self.imageView.layer.masksToBounds = YES; self.imageView.layer.borderWidth = 0; self.imageView.contentMode = UIViewContentModeScaleAspectFill;
添加约束时,只要确保检查高度和宽度,以便修复。 至less,我总是这样做。
您已经给出了leading constraint, trailing constraint
和width constraint.
因此,图像将尝试在图像前后留下130像素,这将增加图像的宽度。
So the solution is, remove either one of the leading or trailing constraint.
最好的解决方法是,删除约束和添加水平中心约束,这是你想要的。
SWIFT 3.x只需更改您的imageView自定义类,并享受。
@IBDesignable class RoundedImageView:UIImageView { @IBInspectable var borderColor:UIColor = UIColor.white { willSet { layer.borderColor = newValue.cgColor } } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = frame.height/2 layer.masksToBounds = true layer.borderWidth = 1 layer.borderColor = borderColor.cgColor } }
更多步骤:
- 添加宽高比约束1:1
- 在属性检查器中标记检查夹边界属性
- 将你的观点转化为你的控制器类
-
将拐angular半径设置为其高度或宽度的一半
yourImageViewOutlet.layer.cornerRadius = yourImageViewOutlet.frame.size.width / 2.0
在故事板中,我将图像设置为“适合缩放”模式
但是,这是一个问题,不是吗? 这意味着:“拉伸图像,使其与图像视图的展开方式相匹配”。 如果那不是你想要的,不要那么说! 使用居中,或至less使用名称中的“Aspect”的内容模式之一,以便您的图像不被拉伸。
至于这个圈子本身,设置cornerRadius
是无法圈出来的。 在图像周围创build圆形边界的方法是屏蔽图像。 您可以使用圆形遮罩重新绘制图像作为剪裁边界,也可以将圆形遮罩应用于图像视图。 (例如,请参阅我的答案: https : //stackoverflow.com/a/16475824/341994 。)
确实,你的形象观也被拉长了,因为你把它限制在超级观的两边。 你可以通过给它一个宽度约束来防止它。 现在它的宽度将是绝对的。 但是在其他两个问题上,你仍然应该做正确的事情。