Reputation: 115
I try change my barbutton image when user load image from photoLibrary or camera. But my barbutton image all time resize and make very big. How i can fix that?
I try use outlet. And here my code
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)
}
If i try make something like this:
photoBarButton.image = image.withRenderingMode(.alwaysOriginal)
Upvotes: 0
Views: 62
Reputation: 6611
You need to resize picked image first. Add below function to resize image:
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
}
}
Add above extension in your code and try to set image in UIBarButtonItem
:
addAppointmentButton.image = pickedImage.resizedImage(newSize: CGSize(width: 24, height: 24))?.withRenderingMode(.alwaysOriginal)
Hope this will help you.
Upvotes: 3