How can i make i circle picture with swift ?
My ViewController :
import UIKit
import Foundation
class FriendsViewController : UIViewController{
// code to make the image round
import UIKit
extension UIImageView {
public func maskCircle(anyImage: UIImage) {
self.contentMode = UIViewContentMode.ScaleAspectFill
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = false
self.clipsToBounds = true
// make square(* must to make circle),
// resize(reduce the kilobyte) and
// fix rotation.
// self.image = prepareImage(anyImage)
}
}
// to call the function from the view controller
self.imgCircleSmallImage.maskCircle(imgCircleSmallImage.image!)
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()
For Swift 4:
import UIKit
extension UIImageView {
func makeRounded() {
let radius = self.frame.width/2.0
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
}
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....
If you mean you want to make a UIImageView circular in Swift you can just use this code:
imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true
If your image is rounded, it would have a height and width of the exact same size (i.e 120). You simply take half of that number and use that in your code (image.layer.cornerRadius = 60).