Is there a way to remove or resize the image from the tag in the Picker view?
Picker("", selection: $selectedCategory) {
ForEach(categorySM.categories, id: \.self) { category in
HStack {
if let inputImage = UIImage(data: category.image ?? Data()) {
Image(uiImage: inputImage)
.resizable()
.scaledToFit()
}
Text(category.name ?? "")
}
.tag(category as CategoryItem?)
}
}
.font(.callout)
.pickerStyle(.menu)
As you can see in images 1 and 2 below, the image in the tag from the Beverages
category is huge and covers almost the entire screen, it also covers the category name (Beverages). Is there a way to remove or resize the image when displaying it on the tag? Basically to make it look like image #3.
Image Link:
https://i.stack.imgur.com/4XpjI.jpg
@Claude31 - Thank you very much for your reply. For some reason resizing the UIImage directly solves the issue.
if let inputImage = UIImage(data: category.image ?? Data()) {
let resizeImage = inputImage.scalePreservingAspectRatio(targetSize: CGSize(width: 25, height: 25))
Image(uiImage: resizeImage)
.resizable()
.scaledToFit()
}
Code for resizing the UIImage
extension UIImage {
func scalePreservingAspectRatio(targetSize: CGSize) -> UIImage {
// Determine the scale factor that preserves aspect ratio
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
let scaleFactor = min(widthRatio, heightRatio)
// Compute the new image size that preserves aspect ratio
let scaledImageSize = CGSize(
width: size.width * scaleFactor,
height: size.height * scaleFactor
)
// Draw and return the resized UIImage
let renderer = UIGraphicsImageRenderer(
size: scaledImageSize
)
let scaledImage = renderer.image { _ in
self.draw(in: CGRect(
origin: .zero,
size: scaledImageSize
))
}
return scaledImage
}
}