问题
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