图像的圆角

时间:2018-08-07 11:30:06

标签: swift uiimageview uicollectionviewcell

我遇到了很奇怪的事情。我有一个具有UICollectionViewCell的自定义UIImageView。现在,我将cornerRadius的{​​{1}}设置为四舍五入,并且可以在某些图像上使用,但是对于其他图像,它会产生如下结果:

enter image description here

您可以清楚地看到图像的顶部和底部没有四舍五入,并且我不确定是什么原因造成的。我认为它与图像的宽度/高度有关,但我无法弄清楚。

我正在UIImageView上使用这个很小的extension来设置舍入的图像。

UIImageView

我尝试将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.widthself.frame.heightself.frame.size.height,它们都产生相同的结果。

1 个答案:

答案 0 :(得分:2)

cornerRadius无关,您的代码(makeRounded())应该四舍五入。

问题与图像视图的contentMode有关。如果您尝试向其添加背景色,则应该能够确切了解问题所在,因此,假设将backgroundColor设置为.red,则应该在其中看到一个红色圆圈,其中包含图像中间。

要解决此问题,您应该选择一种可以填充整个图像视图的内容模式,例如.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
    }
}
相关问题