Search code examples
iosobjective-cswiftrounded-cornerscornerradius

How to set UIImageView with rounded corners for aspect fit mode


I usually use the following code to set rounded corners.

imageView.layer.cornerRadius = 10

It works when the imageView is set at Aspect Fill.

But when the imageView is set to Aspect Fit mode, and the ratio between imageView and picture are different. The rounded corners effect won't be able to tell.

enter image description here

The background color is set to green for showing the rounded corners.

Is there any way to set 'real image part' to rounded corners.

Thank you in advance for your answers.


Solution

  • Use this extension to UIImageView:

    extension UIImageView
    {
        func roundCornersForAspectFit(radius: CGFloat)
        {
            if let image = self.image {
    
                //calculate drawingRect
                let boundsScale = self.bounds.size.width / self.bounds.size.height
                let imageScale = image.size.width / image.size.height
    
                var drawingRect: CGRect = self.bounds
    
                if boundsScale > imageScale {
                    drawingRect.size.width =  drawingRect.size.height * imageScale
                    drawingRect.origin.x = (self.bounds.size.width - drawingRect.size.width) / 2
                } else {
                    drawingRect.size.height = drawingRect.size.width / imageScale
                    drawingRect.origin.y = (self.bounds.size.height - drawingRect.size.height) / 2
                }
                let path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
                let mask = CAShapeLayer()
                mask.path = path.cgPath
                self.layer.mask = mask
            }
        }
    }
    

    Without calling this function

    After calling this extension method