从imagePickerController中选择的图像占用整个屏幕而不是适合UI图像视图[Swift]

时间:2017-06-01 05:03:39

标签: swift uiimageview uiimagepickercontroller

我有一个在容器视图中以编程方式创建的图像视图:

Screen shot with circular profile image view inside container view

我在个人资料图片视图的顶部有一个按钮覆盖图,用于调用图像选择器控制器。从照片库中选择图像时,图像占据整个屏幕,如下所示:

Screenshot after image is selected

以下是此视图控制器的viewDidLoad()和imagePickerController()的代码:

override func viewDidLoad() {
    super.viewDidLoad()

    self.profileBackgroundView.backgroundColor = UIColor.init(red: CGFloat(69.0/255.0), green: CGFloat(171.0/255.0), blue: CGFloat(222.0/255.0), alpha: CGFloat(1))

    //initializePrimaryUserData()

    fullNameTextField.text = self.primaryUser.firstName + self.primaryUser.lastName
    nickNameTextField.text = self.primaryUser.userName

    //create profile image view

    if hasProfilePic {
        profileImage.image = self.primaryUser.image
    } else {
        image = UIImage(named: imageName)!
        profileImage.image = image
    }

    profileImage.frame = CGRect(x: profileBackgroundView.bounds.midX, y: profileBackgroundView.bounds.midY, width: 100, height: 100)

    profileImage.translatesAutoresizingMaskIntoConstraints = false
    profileBackgroundView.addSubview(profileImage)

    profileImage.centerXAnchor.constraint(equalTo: profileBackgroundView.centerXAnchor).isActive = true
    profileImage.centerYAnchor.constraint(equalTo: profileBackgroundView.centerYAnchor).isActive = true

    profileImage.layer.cornerRadius = profileImage.frame.size.width / 2
    profileImage.layer.masksToBounds = false
    profileImage.clipsToBounds = true
    profileImage.contentMode = .scaleAspectFit

    //create profileImageButton
    let profileImageButton = UIButton(frame: CGRect(x: profileBackgroundView.bounds.midX, y: profileBackgroundView.bounds.midY, width: 100, height: 100))
    profileImageButton.setTitle("Photo", for: .normal)
    profileImageButton.addTarget(self, action: #selector(profileImageButtonClicked), for: .touchUpInside)

    profileImageButton.translatesAutoresizingMaskIntoConstraints = false

    profileBackgroundView.addSubview(profileImageButton)

    profileImageButton.centerXAnchor.constraint(equalTo: profileBackgroundView.centerXAnchor).isActive = true
    profileImageButton.centerYAnchor.constraint(equalTo: profileBackgroundView.centerYAnchor).isActive = true

    // Do any additional setup after loading the view.

}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {

        self.primaryUser.image = image
        self.hasProfilePic = true
        self.profileImage.image = image
        self.profileImage.contentMode = .scaleAspectFit
        self.profileImage.clipsToBounds = true
    }

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

1 个答案:

答案 0 :(得分:0)

你可以试试这个

self.profileImage.contentMode = .scaleToFill