簡體   English   中英

如何將圖庫中的圖像設置為 UIButton 背景? 斯威夫特 4

[英]How to set an image from the gallery to UIButton background? Swift 4

我有一個代表用戶頭像的圓形按鈕。 通過單擊此按鈕,我調用了一個 ImagePicker,然后嘗試將拾取的圖像設置為 UIbutton。

首先我這樣做:

@IBAction func choseAvatar(_ sender: Any) {
    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    self.present(image, animated: true, completion: nil)
}

然后這個:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    userAvatar.setImage(image, for: .normal)
    self.dismiss(animated: true, completion: nil)
}

圖像拾取成功,但存在問題。 圖像被拉伸到屏幕底部。 怎么做才對?

在此處輸入圖片說明

我也試過

userAvatar.imageView?.contentMode = .scaleAspectFit
userAvatar.imageView?.image = pickedImage

並且:

userAvatar.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)

有什么想法嗎?

確保為 imageView 正確設置了約束。 確保使用 AspectFit(如果寬度和高度固定,則使用 Fill),並確保啟用了 clipToBounds。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM