90

How can i make i circle picture with swift ?

My ViewController :

import UIKit
import Foundation

class FriendsViewController : UIViewController{

    @IBOutlet weak var profilPicture: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100))
    }
}

My profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100)) do nothing ..

Exemple: http://www.appcoda.com/ios-programming-circular-image-calayer/

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Pixel
  • 1,946
  • 2
  • 15
  • 26
  • 3
    What does "set image in circle" mean? Can you describe more precisely what you want to do? Perhaps draw a picture of the results you want? – matt Jan 21 '15 at 19:00
  • 1
    `profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100))` does not "do nothing". It definitely does something! But what it does is rather unfortunate. It creates a UIImageView and assigns it to a weak reference. The image view is empty; it has no image. Moreover, the reference is weak, so the image view vanishes immediately in a puff of smoke. It's hard to see from this code what you imagined would happen here. – matt Jan 21 '15 at 19:02
  • I want to make this result : http://www.appcoda.com/ios-programming-circular-image-calayer/ – Pixel Jan 21 '15 at 19:03
  • So, now you've added a link to a tutorial that tells you how to do it. So just follow the instructions in that tutorial! You've answered your own question. – matt Jan 21 '15 at 19:03
  • I work in swift when i do the instructions in the tutoriel nothing append :S – Pixel Jan 21 '15 at 19:05

16 Answers16

251
import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()
    
    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.black.cgColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

If you want it on an extension

import UIKit

extension UIImageView {
    
    func makeRounded() {
        
        layer.borderWidth = 1
        layer.masksToBounds = false
        layer.borderColor = UIColor.black.cgColor
        layer.cornerRadius = self.frame.height / 2
        clipsToBounds = true
    }
}

That is all you need....

emrcftci
  • 3,355
  • 3
  • 21
  • 35
Jon
  • 2,526
  • 1
  • 11
  • 2
  • 8
    that `image.clipsToBounds = true` was exactly what I needed :-) – Dave Kliman Mar 14 '16 at 06:26
  • 4
    It doesn't work if UIImageView can grow or shrink due to constrains. In that case it must be inside viewDidLayoutSubviews() – Georgevik Jun 06 '17 at 18:46
  • I found that adding the border around the rounded image leaves a ghost of the original rectangle on the screen. This was visible on Simulator 10.0 and may not occur on a real device, but thought it was significant enough to mention here. – ZacSketches Aug 12 '17 at 22:55
  • `image.layer.borderColor = UIColor.blackColor().CGColor` turns into `image.layer.borderColor = UIColor.black.cgColor` – George Pazdral Dec 18 '17 at 22:14
  • Work perfect in swift 4. – iGhost May 22 '19 at 19:17
  • 1
    You may need to use DispatchQueue: `DispatchQueue.main.async(execute:{ self.imageview.makeRounded() })` – Mahmut K. Jun 16 '20 at 22:01
40

You can simple create extension:

import UIKit

extension UIImageView {

   func setRounded() {
      let radius = CGRectGetWidth(self.frame) / 2
      self.layer.cornerRadius = radius
      self.layer.masksToBounds = true
   }
}

and use it as below:

imageView.setRounded()
ddb
  • 2,423
  • 7
  • 28
  • 38
Daniel Kuta
  • 1,634
  • 15
  • 24
16

Based in the answer of @DanielQ

Swift 4 and Swift 3

import UIKit

extension UIImageView {

    func setRounded() {
        self.layer.cornerRadius = (self.frame.width / 2) //instead of let radius = CGRectGetWidth(self.frame) / 2
        self.layer.masksToBounds = true
    }
}

You can use it in any ViewController with:

imageView.setRounded()
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157
12

If you mean you want to make a UIImageView circular in Swift you can just use this code:

imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true
Tom Spee
  • 9,209
  • 5
  • 31
  • 49
6

Don't know if this helps anyone but I was struggling with this problem for awhile, none of the answers online helped me. For me the problem was I had different heights and widths set on the image in storyboard. I tried every solution on stack and it turns out it was something as simple as that. Once I set them both to 200 my circle profile image was perfect. This was code then in my VC.

profileImage2.layer.cornerRadius = profileImage2.frame.size.width/2
    profileImage2.clipsToBounds = true
Grace
  • 377
  • 3
  • 19
  • Sweet! Thanks. This should be the answer. Two clean lines of code. No need to extend classes or anything extra. – user3286381 Dec 26 '16 at 22:54
6

This way is the least expensive way and always keeps your image view rounded:

class RoundedImageView: UIImageView {

    override init(frame: CGRect) {
        super.init(frame: frame)

        clipsToBounds = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        clipsToBounds = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        assert(bounds.height == bounds.width, "The aspect ratio isn't 1/1. You can never round this image view!")

        layer.cornerRadius = bounds.height / 2
    }
}

The other answers are telling you to make views rounded based on frame calculations set in a UIViewControllers viewDidLoad() method. This isn't correct, since it isn't sure what the final frame will be.

J. Doe
  • 12,159
  • 9
  • 60
  • 114
4

For Swift 4:

import UIKit

extension UIImageView {

func makeRounded() {
    let radius = self.frame.width/2.0
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
   }
}
Ghulam Rasool
  • 3,996
  • 2
  • 27
  • 40
3

All the answers above couldn't solve the problem in my case. My ImageView was placed in a customized UITableViewCell. Therefore I had also call the layoutIfNeeded() method from here. Example:

 class NameTableViewCell:UITableViewCell,UITextFieldDelegate { ...

 override func awakeFromNib() {

    self.layoutIfNeeded()
    profileImageView.layoutIfNeeded()

    profileImageView.isUserInteractionEnabled = true
    let square = profileImageView.frame.size.width < profileImageView.frame.height ? CGSize(width: profileImageView.frame.size.width, height: profileImageView.frame.size.width) : CGSize(width: profileImageView.frame.size.height, height:  profileImageView.frame.size.height)
    profileImageView.addGestureRecognizer(tapGesture)
    profileImageView.layer.cornerRadius = square.width/2
    profileImageView.clipsToBounds = true;
}
Nazar Medeiros
  • 437
  • 4
  • 10
3
struct CircleImage: View {
    var image: Image

    var body: some View {
        image
           .clipShape(Circle())
    }
}

This is correct for SwiftUI

Michal Rogowski
  • 431
  • 3
  • 18
2
extension UIImageView{
   
// Round Image
    func roundCorner() {
        self.layer.masksToBounds = true
        self.layer.borderWidth = 1.0
        self.layer.borderColor = UIColor.clear.cgColor
        self.layer.cornerRadius = self.frame.size.width/2
    }
}
 
RAMNATH T
  • 21
  • 3
1

First you need to set equal width and height for getting Circular ImageView.Below I set width and height as 100,100.If you want to set equal width and height according to your required size,set here.

 var imageCircle = UIImageView(frame: CGRectMake(0, 0, 100, 100))

Then you need to set height/2 for corner radius

 imageCircle.layer.cornerRadius = imageCircle.frame.size.height/2
 imageCircle.layer.borderWidth = 1
 imageCircle.layer.borderColor = UIColor.blueColor().CGColor
 imageCircle.clipsToBounds = true
 self.view.addSubview(imageCircle)
user3182143
  • 9,459
  • 3
  • 32
  • 39
1

For Swift3/Swift4 Developers:

let radius = yourImageView.frame.width / 2
yourImageView.layer.cornerRadius = radius
yourImageView.layer.masksToBounds = true
Achintya Ashok
  • 521
  • 4
  • 9
  • not quite, I think he's adding an extension to ImageView. This is changing the instance of the class directly. If it's not helpful I can take it down. – Achintya Ashok Nov 18 '17 at 18:52
1

For Rounded Image, Only following code would be enough in Extension:

self.layoutIfNeeded() // in case of autolayout(mentioned by Tom Spee in the comment).

And also make sure the property of UIImageView contentMode should be set correctly to get the result. In my case it is:

imageView.contentMode = .scaleAspectFit


extension UIImageView {
    func setRounded() {
            self.layoutIfNeeded()
            self.layer.cornerRadius = self.frame.height / 2
            self.clipsToBounds = true
    }
}
FARAZ
  • 645
  • 7
  • 6
0
// code to make the image round


import UIKit

extension UIImageView {
public func maskCircle(anyImage: UIImage) {


    self.contentMode = UIViewContentMode.ScaleAspectFill
    self.layer.cornerRadius = self.frame.height / 2
    self.layer.masksToBounds = false
    self.clipsToBounds = true




    // make square(* must to make circle),
    // resize(reduce the kilobyte) and
    // fix rotation.
    //        self.image = prepareImage(anyImage)
}
}

// to call the function from the view controller

self.imgCircleSmallImage.maskCircle(imgCircleSmallImage.image!)
Ullas Pujary
  • 349
  • 4
  • 14
0
imageView.layer.cornerRadius = imageView.frame.height/2
imageView.clipToBounds = true
chirag90
  • 2,211
  • 1
  • 22
  • 37
Rishi jha
  • 21
  • 3
-1

If your image is rounded, it would have a height and width of the exact same size (i.e 120). You simply take half of that number and use that in your code (image.layer.cornerRadius = 60).