当用户从照相馆或照相机加载图像时,我尝试更改我的barbutton图像。但是我的barbutton图片一直都在调整大小并变得很大。我该如何解决?
我尝试使用插座。这是我的代码
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
self.imageData = image.pngData()!
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
button.layer.cornerRadius = 0.5
button.clipsToBounds = true
button.setImage(UIImage(data: imageData!), for: .normal)
photoBarButton.customView = button
picker.dismiss(animated: true, completion: nil)
}
如果我尝试做这样的事情:
photoBarButton.image = image.withRenderingMode(.alwaysOriginal)
答案 0 :(得分:3)
您需要先调整所选图像的大小。添加以下功能来调整图像大小:
extension UIImage {
func resizedImage(newSize: CGSize) -> UIImage? {
guard size != newSize else { return self }
let hasAlpha = false
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(newSize, !hasAlpha, scale)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
在代码中添加上述扩展名,然后尝试在UIBarButtonItem
中设置图片:
addAppointmentButton.image = pickedImage.resizedImage(newSize: CGSize(width: 24, height: 24))?.withRenderingMode(.alwaysOriginal)
希望这会对您有所帮助。