Swift Circle Image Rounded Tutorial
Turning a plain old square image to a a nice circle image in Swift is quite simple. In this tutorial you will learn how to do this and also how to create an extension out of it to easily reuse it in your future apps.
First of all create a new single view application. Add the following image of the dog into your project:
Next up add a UIImage to the Main.storyboard and set the image to be our dog, make sure the Width and Height of the image is equal, this is important for a round image.
Next up connect it to our ViewController.swift using the Assistant Editor. Name the outlet imgDoggo.
Then in viewDidLoad() add the following code to make a round image:
imgDoggo.layer.cornerRadius = imgDoggo.frame.size.width / 2 imgDoggo.clipsToBounds = true
Neat – we have a round image now. You can also adjust the corner radius if you want a gentle corner instead of a rounded image. Also you can add a border to the image, example code:
imgDoggo.layer.cornerRadius = 20 imgDoggo.clipsToBounds = true imgDoggo.layer.borderColor = UIColor.blue.cgColor imgDoggo.layer.borderWidth = 4
One handy thing to do is to create an extension. This will keep the code to make a rounded image in one place, you can call it many times from different images with one line in the future, and make changes to the code in one place.
Go File->New->File and create a Swift File. Name the file UIImageView, and change the code to the following:
import UIKit extension UIImageView { func roundedImage() { self.layer.cornerRadius = self.frame.size.width / 2 self.clipsToBounds = true } }
Now to make an image rounded we would simply call it as follows:
imgDoggo.roundedImage()
This is useful as if we wanted to add a red border to all the rounded images in our app we could simply make the change in the one UIImageView extension rather then all the images in the app, saving heaps of time.