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)
}
}
Try this in your UICollectionViewCell
override func awakeFromNib() {
super.awakeFromNib()
DispatchQueue.main.async {
self.image.roundCorners([.topRight,.topLeft], radius: 8)
self.image.layer.masksToBounds = true
}
}
Thanks to AshvinGudaliya and Sujewan
Following code worked for my collection cell's ImageView Top Left-Right corners
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
}
and the extension is
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
}
}
Swift 5
In your collectionview cell, put the below two lines of code & you are good to go. No need to write any extension:
cell._imageView.layer.cornerRadius = 10
cell._imageView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
Here corner radius will apply TopLeft & TopRight corners & rest of corners will remain same.
If you want to apply the corner radius in BottomLeft & BottomRight corners, then maskedCorners should look like the below:
cell._imageView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.