How to set imageView in circle like imageContacts in Swift correctly?
Asked Answered
C

24

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!

Commissar answered 30/8, 2014 at 23:46 Comment(1)
here is solution for case the imageview had Width different with Height: #29685555Sension
O
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))
Otolith answered 31/8, 2014 at 1:29 Comment(4)
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?Ridgley
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.Asceticism
This is actually the only correct answer, if you don't set your imageView to square none of other answers will work.Trunk
"'CGRectMake' is unavailable in Swift".Remaremain
L
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
Lodged answered 11/5, 2015 at 11:59 Comment(2)
Why all answers here so up-voted so much? isn't it a bit stupid to use cornerRadius there is image don't have to be square?Nab
"Value of type 'UIImage?' has no member 'frame'". Hmmmm.Remaremain
O
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))
Otolith answered 31/8, 2014 at 1:29 Comment(4)
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?Ridgley
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.Asceticism
This is actually the only correct answer, if you don't set your imageView to square none of other answers will work.Trunk
"'CGRectMake' is unavailable in Swift".Remaremain
P
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)
Pappano answered 19/3, 2016 at 14:23 Comment(3)
I cannot find prepareImage() method. Has it been changed?Walkout
@Walkout that is his custom func... you just use self.image = anyImageGymno
I removed extra function. Thank you @BorisNikolićPappano
O
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 .

Outlook answered 10/8, 2018 at 5:53 Comment(0)
B
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
    }
}
Brawny answered 16/7, 2017 at 8:3 Comment(0)
E
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
Endogen answered 11/2, 2016 at 21:46 Comment(0)
H
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
Hae answered 3/6, 2015 at 5:37 Comment(2)
Do you need to import quartzcore for this?Fregger
@Fregger nope.!Hae
J
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
}
Jett answered 22/3, 2018 at 18:46 Comment(2)
adding the corner radius code to viewWillLayoutSubviews worked for me to make my ImageView a perfect circleTedtedd
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. ThanksMongol
Y
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() 
Yuonneyup answered 29/3, 2019 at 14:29 Comment(0)
D
3
reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true
Dissentious answered 25/3, 2017 at 14:5 Comment(0)
O
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))

Office answered 13/5, 2016 at 11:15 Comment(0)
Z
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.

Zonnya answered 24/6, 2017 at 21:40 Comment(0)
M
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
}
Moss answered 10/10, 2017 at 14:48 Comment(0)
R
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

Roaster answered 8/4, 2016 at 0:26 Comment(0)
V
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)
Vibration answered 11/4, 2016 at 10:58 Comment(0)
S
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
Selfrevealing answered 28/3, 2017 at 16:4 Comment(0)
D
1

Use this code to make image round

     self.layoutIfNeeded()
     self.imageView.layer.cornerRadius = 
     self.imageView.frame.width/2
     self.imageView.layer.masksToBounds = true
Darwinism answered 31/1, 2018 at 9:32 Comment(0)
W
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.
Wulfe answered 17/2, 2020 at 22:37 Comment(0)
T
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)
        }
    }
}
Teteak answered 16/4, 2020 at 18:53 Comment(0)
S
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

Suffragist answered 13/10, 2020 at 18:56 Comment(0)
A
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
        }
    }
    
}
Acrostic answered 20/12, 2020 at 21:22 Comment(0)
S
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.

Sleuth answered 29/12, 2021 at 7:9 Comment(0)
R
0

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

Reel answered 31/8, 2022 at 12:10 Comment(0)
B
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
    }()
Barling answered 12/12, 2022 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.