Samuel Kith
Samuel Kith

Reputation: 119

How to create a circular UIImageView

I am having issue creating a circular UIImageView. If I were to manually set the corderRadius to a value, eg. 50, it will have rounded corner. But when I try to set it as half of the frame's height or width (frame.width / 2 or frame.height / 2), it doesn't work. Somehow, the frame is (0, 0, 0, 0) when I try to print it.

And here is my code,

import UIKit

class TestIconController : UIViewController {

let icon: UIImageView = {
    let imageView = UIImageView()
    imageView.layer.cornerRadius = imageView.frame.width / 2
    imageView.clipsToBounds = true
    imageView.layer.masksToBounds = true
    imageView.backgroundColor = .red
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

override func viewDidLoad() {
    super.viewDidLoad()
    loadLogo()
}

func loadLogo() {
    view.addSubview(icon)

    // Constraints
    icon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    icon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    icon.heightAnchor.constraint(equalToConstant: 200).isActive = true
    icon.widthAnchor.constraint(equalToConstant: 200).isActive = true
  }

}

Upvotes: 1

Views: 108

Answers (3)

Eugene Lezov
Eugene Lezov

Reputation: 770

You can create this extensions

extension UIImageView {

    func setRounded() {
        self.layer.cornerRadius = self.frame.width / 2
        self.layer.masksToBounds = true
        self.clipsToBounds = true
    }
}

In your case you can inside viewDidLayoutSubviews call

icon.setRounded()

Upvotes: 0

Shoaib
Shoaib

Reputation: 2294

You may also make a base class for it for batter handling; Like

class UICirlceImageView : UIImageView {
    override open func layoutSubviews() {
        super.layoutSubviews();

        let layer:CALayer = self.layer;
        layer.cornerRadius = self.frame.size.width/2.0;
        layer.masksToBounds = true;
    }
}

then, do it like this

//let icon: UICirlceImageView = { // You may initialize like this as well
let icon: UIImageView = {
    let imageView = UICirlceImageView()
    imageView.backgroundColor = .red
    //imageView.translatesAutoresizingMaskIntoConstraints = false // Don't know if it is needed
    return imageView
}()

Note: The answer given by Rushabh is also correct.

Upvotes: 1

Rushabh Shah
Rushabh Shah

Reputation: 398

Override this function.

override func viewDidLayoutSubviews() {
        icon.layer.cornerRadius = icon.bounds.size.width / 2
        icon.clipsToBounds = true
        icon.layer.masksToBounds = true
    }

Upvotes: 3

Related Questions