How to display an image with rounded corners on iOS App using Swift?

iOSiPhone/iPadMobile Development

To make an image with round corners or to make any view or button or any UI element with round corners in swift, we need to access the corner radius property of its layer. Every UI element in iOS is based on a layer.

First of all, let’s add an UIImageView Object in our storyboard. Or let’s create one programmatically.

Below is a function that will programmatically create an image view and add an image to it.

func addImage(imageName img: String) {
   let imageView = UIImageView()
   imageView.frame = CGRect(x: 10, y: 20, width: 200, height: 200)
   imageView.contentMode = . scaleAspectFill
   if let newImage = UIImage(named: img) {
      imageView.image = newImage
   }
   self.view.addSubview(imageView)
}

Let’s suppose the original image that we want to add in our application is −

in our viewDidLoad, let’s call the code below to add this image to our application.

Below is how it looks without any change to its corner property.

Now, let’s add the corner radius property to our existing code and see how it looks.

imageView.layer.cornerRadius = 10
imageView.clipsToBounds = true

Add these two lines in the addImage function, right above the addSubview method. When we run the application this is how it looks now −

We can also create an extension of UIImageView and use the same like as shown below, which again produces the same result.

extension UIImageView {
   func makeRoundCorners(byRadius rad: CGFloat) {
      self.layer.cornerRadius = rad
      self.clipsToBounds = true
   }
}


imageView.makeRoundCorners(byRadius: 20)
raja
Published on 30-Jan-2019 10:22:51
Advertisements