user3745888
user3745888

Reputation: 6353

How to set imageView in circle like imageContacts in Swift correctly?

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!

Upvotes: 60

Views: 116511

Answers (24)

Rıdvan Yılmaz
Rıdvan Yılmaz

Reputation: 1

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
    }()

Upvotes: 0

Hafiz Anser
Hafiz Anser

Reputation: 581

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.

Upvotes: 1

EAO123
EAO123

Reputation: 67

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

Upvotes: 0

Rattanakoudom Sambath
Rattanakoudom Sambath

Reputation: 544

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.

Upvotes: 0

Alan Hewitt
Alan Hewitt

Reputation: 11

// 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)
        }
    }
}

Upvotes: 1

user14853368
user14853368

Reputation:

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

Upvotes: 0

Menaim
Menaim

Reputation: 1014

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

Upvotes: 1

Codetard
Codetard

Reputation: 2605

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

Upvotes: 7

Lance Samaria
Lance Samaria

Reputation: 19622

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
}

Upvotes: 5

Dhanu K
Dhanu K

Reputation: 12443

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() 

Upvotes: 5

Jaywant Khedkar
Jaywant Khedkar

Reputation: 6141

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 .

Upvotes: 11

Nithinbemitk
Nithinbemitk

Reputation: 2740

Use this code to make image round

     self.layoutIfNeeded()
     self.imageView.layer.cornerRadius = 
     self.imageView.frame.width/2
     self.imageView.layer.masksToBounds = true

Upvotes: 1

Manu Gupta
Manu Gupta

Reputation: 1759

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

Upvotes: 57

Akhil Clement
Akhil Clement

Reputation: 685

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
}

Upvotes: 2

Sai kumar Reddy
Sai kumar Reddy

Reputation: 1829

reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true

Upvotes: 3

iluvatar_GR
iluvatar_GR

Reputation: 1017

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

Upvotes: 9

cph2117
cph2117

Reputation: 2681

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.

Upvotes: 2

fatihyildizhan
fatihyildizhan

Reputation: 8832

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)

Upvotes: 21

handiansom
handiansom

Reputation: 783

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

Upvotes: 1

Umair Afzal
Umair Afzal

Reputation: 5049

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))

Upvotes: 2

Sahli Simo
Sahli Simo

Reputation: 87

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)

Upvotes: 1

Nicolas2bert
Nicolas2bert

Reputation: 1152

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

Upvotes: 1

jsanabria
jsanabria

Reputation: 451

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

Upvotes: 8

chazkii
chazkii

Reputation: 1310

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))

Upvotes: 46

Related Questions