繁体   English   中英

Swift 4 - 快速带有两个圆角的图像视图?

[英]Swift 4 - imageview with two rounded corners in swift?

我在 UICollectionView 单元格中有一个 UIImageView,我想让它的顶角变圆。 我无法解决我的问题,任何帮助表示赞赏。

您可以看到单元格的角半径为 10 像素,我也希望在图像上应用相同的效果。

恩德克萨

您可以在此处尝试UIRectCorner文档

这里是我的自定义类AGRoundCornersView

extension UIImageView {
    public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: bounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape
    }
}

代码:

1. 调整视图大小时调用。

uiimage.roundCorners([.topLeft, .topRight], radius: 10)

2. 创建自定义类

class CustomImageView: UIImageView {
    override func layoutSubviews() {
        super.layoutSubviews()
        self.roundCorners([.topLeft, .topRight], radius: 10)
    }
}

在你的 UICollectionViewCell 中试试这个

 override func awakeFromNib() {
        super.awakeFromNib()
        DispatchQueue.main.async {
            self.image.roundCorners([.topRight,.topLeft], radius: 8)
            self.image.layer.masksToBounds = true
        }
    }

感谢AshvinGudaliyaSujewan

以下代码适用于我的集合单元格的 ImageView 左上角

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:TUGBucketCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! TUGBucketCell
        //Rounded corner ImageView
        DispatchQueue.main.async {
            cell.imgVw.roundCorners([.topLeft, .topRight], radius: 10)
            cell.imgVw.layer.masksToBounds = true
        }

        return cell
    }

和扩展是

extension UIImageView {
    public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: bounds,
                                    byRoundingCorners: corners,
                                    cornerRadii: CGSize(width: radius, height: radius))
        let shape = CAShapeLayer()
        shape.path = maskPath.cgPath
        layer.mask = shape
    }
}

斯威夫特 5

在您的 collectionview 单元格中,放入以下两行代码,您就可以开始了。 无需编写任何扩展:

cell._imageView.layer.cornerRadius = 10
cell._imageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]

这里角半径将应用TopLeft 和 TopRight角,其余角将保持不变。

如果要在BottomLeft 和BottomRight角应用圆角半径,则maskedCorners应如下所示:

cell._imageView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]

希望它有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM