iosswiftimageuiimageviewcornerradius

How to set corner Radius to UIImage not UIImageView in iOS Swift


Can any one help me...! I just want to set a corner radius to an image and also the image has to be fit in AspectFit scale.

If I give scaleToFill mode I can use the below code and its working fine. but the image is been Stretched.

self.productImg.layer.cornerRadius = 7
self.productImg.clipsToBounds = true

But when giving the scale to AspectFit it is showing as shown in below image.

The green color showing is the image View, and within that the image is setting to aspectFit.

The Actual image

Actual image

The Image when giving the aspectFit mode

Image when giving the aspectFit mode

i need the image as it is actually given and also it has to be with corner radius. So please any one give me solution to Resolve this.

Thanks in Advance...!


Solution

  • Here is an extension for UIImage to set corner radius for it, not dealing with UIImageView.

    extension UIImage {
        // image with rounded corners
        public func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
            let maxRadius = min(size.width, size.height) / 2
            let cornerRadius: CGFloat
            if let radius = radius, radius > 0 && radius <= maxRadius {
                cornerRadius = radius
            } else {
                cornerRadius = maxRadius
            }
            UIGraphicsBeginImageContextWithOptions(size, false, scale)
            let rect = CGRect(origin: .zero, size: size)
            UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
            draw(in: rect)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return image
        }
    }   
    

    Usage:

    yourUIImage.withRoundedCorners(radius: 10)