How to set image in circle in swift
How can i make i circle picture with swift ?
My ViewController :
import UIKit
import Foundation
class FriendsViewController : UIViewController{
@IBOutlet weak var profilPicture: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100))
}
}
My profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100))
do nothing ..
Exemple: http://www.appcoda.com/ios-programming-circular-image-calayer/
Solution 1:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
image.layer.borderWidth = 1
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.black.cgColor
image.layer.cornerRadius = image.frame.height/2
image.clipsToBounds = true
}
If you want it on an extension
import UIKit
extension UIImageView {
func makeRounded() {
self.layer.borderWidth = 1
self.layer.masksToBounds = false
self.layer.borderColor = UIColor.black.cgColor
self.layer.cornerRadius = self.frame.height / 2
self.clipsToBounds = true
}
}
That is all you need....
Solution 2:
You can simple create extension:
import UIKit
extension UIImageView {
func setRounded() {
let radius = CGRectGetWidth(self.frame) / 2
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
and use it as below:
imageView.setRounded()
Solution 3:
Based in the answer of @DanielQ
Swift 4 and Swift 3
import UIKit
extension UIImageView {
func setRounded() {
self.layer.cornerRadius = (self.frame.width / 2) //instead of let radius = CGRectGetWidth(self.frame) / 2
self.layer.masksToBounds = true
}
}
You can use it in any ViewController
with:
imageView.setRounded()