Search code examples
iosswiftxcodeuiimageviewcalayer

How to make a round shape editing area instead of a rectangle for ImagePicker?


enter image description hereI have registration form for users where users can add their photo for profile. I create round shape for imageView, but when I choose photo from library photo is not rounded and goes beyond

class SigninViewController: UIViewController {


var imagePicker = UIImagePickerController()

@IBOutlet var countPlaceInCar: UITextField!
@IBOutlet var nameOfCar: UITextField!

@IBOutlet var AddPhotoButton: UIButton!
@IBOutlet var registerButton: UIButton!

@IBOutlet var registrationSegmented: UISegmentedControl!


@IBOutlet var addPhotoImage: UIImageView!



override func viewDidLoad() {
    super.viewDidLoad()
    makeRounded()
    imagePicker.delegate = self
 }

//func that rounded image for user
func makeRounded() {
    addPhotoImage.layer.borderWidth = 1
    addPhotoImage.layer.masksToBounds = false
    addPhotoImage.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    addPhotoImage.layer.cornerRadius = addPhotoImage.frame.height/2 //This will change with corners of image and height/2 will make this circle shape

}

@IBAction func addPhotoFromLibraryOrCamera(_ sender: UIButton) {
    imagePicker.sourceType = .photoLibrary
    imagePicker.allowsEditing = true
    present(imagePicker, animated: true, completion: nil)

   }  
}

extension SigninViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            addPhotoImage.image = image


        }
        dismiss(animated: true, completion: nil)
    }
}

Solution

  • Simply set masksToBounds to true:

    func makeRounded() {
        addPhotoImage.layer.borderWidth = 1
        addPhotoImage.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        addPhotoImage.layer.cornerRadius = addPhotoImage.frame.height/2 //This will change with corners of image and height/2 will make this circle shape
        addPhotoImage.layer.masksToBounds = true
    }