60

I want to show a picture into imageView like the image contact (in a circle) But when I try to show this, the imageView rescale his size and this doesn't show correctly in a circle.

 image.layer.borderWidth=1.0
 image.layer.masksToBounds = false
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.clipsToBounds = true

I want to show like this: enter image description here

But I get this: enter image description here

How can do the image resize to UIImageView size to show as a circle?

Thanks!

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
user3745888
  • 6,143
  • 15
  • 48
  • 97
  • here is solution for case the imageview had Width different with Height: http://stackoverflow.com/questions/29685055/ios-frame-size-width-2-doesnt-produce-a-circle-on-every-device – lee Aug 18 '16 at 04:29

24 Answers24

57

This is solution which I have used in my app:

var image: UIImage = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.cornerRadius = image.frame.size.width/2
imageView.clipsToBounds = true

Swift 4.0

let image = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.cornerRadius = image.frame.size.width / 2
imageView.clipsToBounds = true
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Manu Gupta
  • 1,759
  • 1
  • 14
  • 22
46

What frame size are you using for image? I can get a perfect circle if I set the frame to be a square.

let image = UIImageView(frame: CGRectMake(0, 0, 100, 100))
chazkii
  • 1,300
  • 12
  • 21
  • my image size in the size inspector is set to 120 width and 120 height, yet when I run it, it's not a perfect circle because the width turns out to be a bit longer? Why? – LuKenneth Jan 21 '16 at 19:08
  • 1
    If the frame is a square, setting the radius to half the width/height will always give you a circular view. If one is creating a custom class that might accomadate various squared frame sizes, one mustn't hardcode the radius value. –  Feb 27 '16 at 06:44
  • This is actually the only correct answer, if you don't set your imageView to square none of other answers will work. – bojan May 20 '20 at 19:25
  • "'CGRectMake' is unavailable in Swift". – Chris Neve Apr 22 '21 at 20:35
21

Fast and Simple solution.

How to mask UIImage to Circle without cropping with Swift.

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 = anyImage
  }
}

How to call:

let anyAvatarImage:UIImage = UIImage(named: "avatar")!
avatarImageView.maskCircle(anyAvatarImage)
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
11

Try this it's work for me ,

set imageView width and height same .

Swift

imageview?.layer.cornerRadius = (imageview?.frame.size.width ?? 0.0) / 2     
imageview?.clipsToBounds = true
imageview?.layer.borderWidth = 3.0
imageview?.layer.borderColor = UIColor.white.cgColor

Screenshot enter image description here

Objective C

self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
self.imageView.clipsToBounds = YES;
self.imageView.layer.borderWidth = 3.0f;
self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;

Hope this will help to some one .

Jaywant Khedkar
  • 5,941
  • 2
  • 44
  • 55
9

Create your custom circle UIImageView and create the circle under the layoutSubviews helps if you use Autolayout.

/*
      +-------------+
      |             |
      |             |
      |             |
      |             |
      |             |
      |             |
      +-------------+
  The IMAGE MUST BE SQUARE
*/
class roundImageView: UIImageView {

    override init(frame: CGRect) {
        // 1. setup any properties here
        // 2. call super.init(frame:)
        super.init(frame: frame)
        // 3. Setup view from .xib file
    }

    required init?(coder aDecoder: NSCoder) {
        // 1. setup any properties here
        // 2. call super.init(coder:)
        super.init(coder: aDecoder)
        // 3. Setup view from .xib file
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layer.borderWidth = 1
        self.layer.masksToBounds = false
        self.layer.borderColor = UIColor.white.cgColor
        self.layer.cornerRadius = self.frame.size.width/2
        self.clipsToBounds = true
    }
}
iluvatar_GR
  • 1,017
  • 13
  • 19
8

I would suggest making your image file a perfect square to begin with. This can be done in almost any photo editing program. After that, this should work within viewDidLoad. Credit to this video

image.layer.cornerRadius = image.frame.size.width/2
image.clipsToBounds = true
jsanabria
  • 451
  • 6
  • 8
7

That is all you need....

        profilepic = UIImageView(frame: CGRectMake(0, 0, self.view.bounds.width * 0.19 , self.view.bounds.height * 0.1))
        profilepic.layer.borderWidth = 1
        profilepic.layer.masksToBounds = false
        profilepic.layer.borderColor = UIColor.blackColor().CGColor
        profilepic.layer.cornerRadius = profilepic.frame.height/2
        profilepic.clipsToBounds = true
Codetard
  • 2,441
  • 28
  • 34
5

If your using a UIViewController here's how do do it using Anchors. The key is to set the imageView's layer.cornerRadius in viewWillLayoutSubviews like so:

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

Also make sure the heightAnchor and widthAnchor are the same size. They are both 100 in my example below

Code:

let imageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.layer.borderWidth = 1.0
    imageView.clipsToBounds = true
    imageView.layer.borderColor = UIColor.white.cgColor
    return imageView
}()


override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(imageView)

    imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true

    imageView.image = UIImage(named: "pizzaImage")
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}

If your using a CollectionView Cell set the imageView's layer.cornerRadius in layoutSubviews():

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

    addSubview(imageView)

    imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
    imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
    imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 50).isActive = true

    imageView.image = UIImage(named: "pizzaImage")

}

override func layoutSubviews() {
    super.layoutSubviews() // call super.layoutSubviews()
    imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
Lance Samaria
  • 17,576
  • 18
  • 108
  • 256
  • adding the corner radius code to `viewWillLayoutSubviews` worked for me to make my ImageView a perfect circle – Anna Harrison Sep 21 '19 at 15:36
  • adding corner radius to viewWillLayoutSubviews when imageview is anchor through the storyboard worked for me for all devices, I had an issue when it worked for iPhone X or greater but did not work for iPhone 8. Thanks – clopex Feb 24 '21 at 14:44
5

this extension really works for me (including in swift 4+)

extension UIImageView {
    func roundedImage() {
        self.layer.cornerRadius = (self.frame.size.width) / 2;
        self.clipsToBounds = true
        self.layer.borderWidth = 3.0
        self.layer.borderColor = UIColor.white.cgColor
    }
}

Then simply call it as

imageView.roundedImage() 
Dhanu K
  • 11,288
  • 6
  • 24
  • 38
3
reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true
Sai kumar Reddy
  • 1,751
  • 20
  • 23
2

what i found out is that your width and height of image view must return an even number when divided by 2 to get a perfect circle e.g

let image = UIImageView(frame: CGRectMake(0, 0, 120, 120))

it should not be something like let image = UIImageView(frame: CGRectMake(0, 0, 130, 130))

Umair Afzal
  • 4,947
  • 5
  • 25
  • 50
2

I had a similar result (more of an oval than a circle). It turned out that the constraints I set on the UIImageView forced it into an oval instead of a circle. After fixing that, the above solutions worked.

cph2117
  • 2,651
  • 1
  • 28
  • 41
2

try this. swift code

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    perform(#selector(self.setCircleForImage(_:)), with: pickedImage, afterDelay: 0)
}


 @objc func setCircleForImage(_ imageView : UIImageView){
    imageView.layer.cornerRadius = pickedImage.frame.size.width/2
    imageView.clipsToBounds = true
}
Akhil Clement
  • 575
  • 1
  • 7
  • 17
1

I fixed it doing modifying the view:

  1. Go to your Main.storyboard
  2. Click on your image
  3. View -> Mode -> Aspect Fill

It works perfectly

Nicolas2bert
  • 1,142
  • 7
  • 10
1

This work perfectly for me. The order of lines is important

func circularImage(photoImageView: UIImageView?)
{
    photoImageView!.layer.frame = CGRectInset(photoImageView!.layer.frame, 0, 0)
    photoImageView!.layer.borderColor = UIColor.grayColor().CGColor
    photoImageView!.layer.cornerRadius = photoImageView!.frame.height/2
    photoImageView!.layer.masksToBounds = false
    photoImageView!.clipsToBounds = true
    photoImageView!.layer.borderWidth = 0.5
    photoImageView!.contentMode = UIViewContentMode.ScaleAspectFill
}

How to use:

    @IBOutlet weak var photoImageView: UIImageView!
    ...
    ...
    circularImage(photoImageView)
Sahli Simo
  • 85
  • 2
  • 7
1

This also works for me. For perfect circle result, use the same size for width and height. like image.frame = CGRect(0,0,200, 200)

For non perfect circle, width and height should not be equal like this codes below.

 image.frame = CGRect(0,0,200, 160)
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.layer.masksToBounds = false
 image.layer.clipsToBounds = true
 image.contentMode = .scaleAspectFill
handiansom
  • 783
  • 11
  • 27
1

Use this code to make image round

     self.layoutIfNeeded()
     self.imageView.layer.cornerRadius = 
     self.imageView.frame.width/2
     self.imageView.layer.masksToBounds = true
Nithinbemitk
  • 2,710
  • 4
  • 24
  • 27
1

You need to make sure the height and width should be the same as your image/view.

  1. Like an image with 100 widths and 100 height sizes (100 X 100). If the sizes are different then the circle does not look like a circle.
HafizAnser
  • 553
  • 6
  • 10
1
// MARK: ImageView extension to make rounded   
@IBDesignable extension UIImageView {

    @IBInspectable var masksToBounds: Bool {
        set {
            layer.masksToBounds = newValue
        }
        get {
            return layer.masksToBounds
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    
    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
        }
        get {
            return layer.cornerRadius
        }
    }
    
    @IBInspectable var borderColor: UIColor? {
        set {
            guard let uiColor = newValue else { return }
            layer.borderColor = uiColor.cgColor
        }
        get {
            guard let color = layer.borderColor else { return nil }
            return UIColor(cgColor: color)
        }
    }
}
Yehor Androsov
  • 4,885
  • 2
  • 23
  • 40
1

You can add this file extension to your project & Don't forget to make your image Square "Width = Height" and you can grantee it by giving the image width and Aspect Ratio (1:1)

import Foundation
import UIKit


extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!)
            return color
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    
}

Then you will write this line in the cell or view controller or wherever you use your image:

imageViewCountryImage.cornerRadius = imageViewCountryImage.frame.height / 2

and you will find your image very super circular

Menaim
  • 937
  • 7
  • 28
0

You can add this extension to your code

import Foundation
import UIKit


extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            let color = UIColor(cgColor: layer.borderColor!)
            return color
        }
        set {
            layer.borderColor = newValue?.cgColor
        }
    }
    
}
0

Just add this extension
Extension:

extension UIImageView { 

    func circleImageView() {
       layer.borderColor = UIColor.white.cgColor
       layer.borderWidth = 2
       contentMode = .scaleAspectFill
       layer.cornerRadius = self.frame.height / 2
       layer.masksToBounds = false
       clipsToBounds = true
    }
}

Controller:

self.imageView?.circleImageView()

One more thing, in order to make the image circle we've to set both width and height equal to each other.

0

Make sure that your height and width of your UIImageView is equal, or else it will look elliptical.

EAO123
  • 55
  • 9
0

I have solved this problem with using these codes

private let profileAvatarImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = imageView.frame.width/2
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.image = UIImage(systemName: "person")
        imageView.backgroundColor = .black
        imageView.layer.borderWidth = 2.0
        imageView.layer.borderColor = UIColor.black.cgColor
        return imageView
    }()