我知道不可能在.scaledToFit()
帧为 120 和 430 的图像上使用修改器,.frame(height: 100, width: 100)
并期望图像以某种方式保持纵横比并适合宽度为 100 和高度为 100 的帧。
因此,似乎解决此问题的唯一方法是强制用户在使用图像选择器上传图像时将图像裁剪为正方形。这在 SwiftUI 中是否可行/我在这里遗漏了什么?
谢谢
我知道不可能在.scaledToFit()
帧为 120 和 430 的图像上使用修改器,.frame(height: 100, width: 100)
并期望图像以某种方式保持纵横比并适合宽度为 100 和高度为 100 的帧。
因此,似乎解决此问题的唯一方法是强制用户在使用图像选择器上传图像时将图像裁剪为正方形。这在 SwiftUI 中是否可行/我在这里遗漏了什么?
谢谢
您可以使用aspectRatio(contentMode:)
:
Image("imageName")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(height: 100, width: 100)
如果我正确理解您的问题,您想将非方形图像 (120x430) 放入方形框 (100x100) 中。为此,您可以缩放图像并保留其纵横比。图像将缩放到最大高度或宽度(取决于目标宽度和高度)。
查看这篇文章:https ://www.robertpieta.com/resize-uiimage-no-stretching-swift/
这是复制和粘贴解决方案:
extension UIImage {
func scalePreservingAspectRatio(width: Int, height: Int) -> UIImage {
let widthRatio = CGFloat(width) / size.width
let heightRatio = CGFloat(height) / size.height
let scaleFactor = min(widthRatio, heightRatio)
let scaledImageSize = CGSize(
width: size.width * scaleFactor,
height: size.height * scaleFactor
)
let format = UIGraphicsImageRendererFormat()
format.scale = 1
let renderer = UIGraphicsImageRenderer(
size: scaledImageSize,
format: format
)
let scaledImage = renderer.image { _ in
self.draw(in: CGRect(
origin: .zero,
size: scaledImageSize
))
}
return scaledImage
}
}