Gorib Developer
Gorib Developer

Reputation: 597

How to make image view round in swift 4

enter image description hereThough there is solution of this question is present in internet, but I am unable to do so, I want to round a image.

this code I am using:

extension UIImageView {        
    func makeRounded() {
        let radius = self.frame.width/2.0
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
 }

then i call this function in viewdidload() like imgvw.makeRounded(). but it is not coming. please help

the previous link is not helping me

Upvotes: 0

Views: 13536

Answers (4)

Snow Star
Snow Star

Reputation: 86

My code works well.

avatar.layer.borderWidth = 1
avatar.layer.masksToBounds = false
avatar.layer.borderColor = UIColor(hexString: "#39B44E").cgColor
avatar.layer.cornerRadius = avatar.frame.height/2 //This will change with corners of image and height/2 will make this circle shape
avatar.clipsToBounds = true

Upvotes: 0

J. Doe
J. Doe

Reputation: 13023

Overriding viewDidLayoutSubviews will unnessecary call the function makeRounded() because it will get called EVERY TIME some layout happens in the superview. You should use this:

class RoundedImageView: UIImageView {

    @override func layoutSubviews() {
        super.layoutSubviews()
        let radius = self.frame.width/2.0
        layer.cornerRadius = radius
        clipsToBounds = true // This could get called in the (requiered) initializer
        // or, ofcourse, in the interface builder if you are working with storyboards
    }

}

Set the class of your imageView to RoundedImageView

Upvotes: 5

Vincent Mungai
Vincent Mungai

Reputation: 302

Create an extension for your class

extension ViewController: UIViewController{

    func makeRounded() {

        layer.borderWidth = 1
        layer.masksToBounds = false
        layer.borderColor = UIColor.blackColor().CGColor
        layer.cornerRadius = frame.height/2 
        clipsToBounds = true
    }

}

Then call use it

imageView.makeRounded()

Upvotes: -2

Aleem
Aleem

Reputation: 3291

import UIKit

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

  func makeRounded() {

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.blackColor().CGColor
    image.layer.cornerRadius = image.frame.height/2 //This will change with corners of image and height/2 will make this circle shape
    image.clipsToBounds = true
}

Happy Coding

Upvotes: 8

Related Questions