How to make image view round in swift 4

青春壹個敷衍的年華 提交于 2019-12-08 15:02:32

问题


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


回答1:


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




回答2:


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
        clipToBounds = 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




回答3:


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


来源:https://stackoverflow.com/questions/49790691/how-to-make-image-view-round-in-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!