我有一个用户注册表格,用户可以在其中添加自己的照片作为个人资料。我为imageView创建了一个圆形,但是当我从库中选择照片时,照片不是圆形的并且超出了范围
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)
}
}
答案 0 :(得分:2)
只需将masksToBounds
设置为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
}