swift 在选取器视图中选择项目时是否移除图像或调整图像大小?

c9qzyr3d  于 2023-09-30  发布在  Swift
关注(0)|答案(1)|浏览(110)

有没有办法在选择器视图中从标签中删除图像或调整图像大小?

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)

正如你在下面的图片1和2中看到的,来自Beverages类别的标签中的图片很大,几乎覆盖了整个屏幕,它还覆盖了类别名称(Bestrom)。在标签上显示图像时,是否有方法删除图像或调整图像大小?让它看起来像图片#3。

lfapxunr

lfapxunr1#

奇怪的是,在转换为Image视图之前调整UIImage的大小解决了这个问题。

if let inputImage = UIImage(data: category.image ?? Data()) {
        let resizeImage = inputImage.scalePreservingAspectRatio(targetSize: CGSize(width: 25, height: 25))
        Image(uiImage: resizeImage)
        .resizable()
        .scaledToFit()
    }

编码为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
        }
    }

相关问题