Reputation: 597
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
Upvotes: 0
Views: 13536
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
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
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
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