Search code examples
iosswiftuicollectionviewuiimageviewswift4

Swift 4 - imageview with two rounded corners in swift?


I have a UIImageView inside of a UICollectionView Cell and I wanna make it' s top corners rounded. I couldn' t solve on my on, any help is appreciated.

You can see cell has 10px corner radius and I want same effect to be applied on image too.

Endeksa


Solution

  • You can try UIRectCorner Document here

    here my custom class 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
        }
    }
    

    code :

    1. Call When View is resized.

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

    2. Create custom class

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