简体   繁体   中英

How to make image view round in swift 4

在此处输入图片说明 Though 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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM