我遇到了一些非常奇怪的事情。我有一个自定义的 UICollectionViewCell
,它有一个 UIImageView
。现在,我将 UIImageView
的 cornerRadius
设置为圆形,它适用于某些图像,但对于其他图像,它会产生如下结果:
你可以清楚地看到图像的顶部和底部没有圆角,我不确定是什么原因造成的。我认为它与图像的宽度/高度有关,但我无法弄清楚。
我在 UIImageView
上使用这个小的 extension
来设置圆形图像。
extension UIImageView {
func makeRounded() {
let radius = self.bounds.height / 2.0
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
我尝试将 self.bounds.height
更改为 self.bounds.width
,但没有任何变化。我尝试使用 self.frame.height
、self.frame.size.height
、self.frame.width
,都产生相同的结果。
最佳答案
它与 cornerRadius
无关,您的代码 (makeRounded()
) 应该使它变圆。
问题与 ImageView 的 contentMode
有关。如果您尝试为其添加背景颜色,您应该能够准确理解问题所在,假设将 backgroundColor
设置为 .red
,您应该会看到中间包含图像的红色圆圈。
要修复它,您应该选择一种内容模式来填充整个 ImageView ,例如 .scaleToFill
或 .scaleAspectFill
:
extension UIImageView {
func makeRounded() {
let radius = self.bounds.height / 2.0
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
self.clipsToBounds = true
// add this one:
self.contentMode = .scaleAspectFill
}
}
关于swift - 图像的圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51725717/