我知道在使用.frame(height: 100, width: 100)
等框架修饰符的情况下,无法在大小为120和430的框架上使用.scaledToFit()
修饰符,并期望图像以某种方式保持长宽比并适合100x100的框架。
所以,似乎唯一的解决方法是强制用户在使用图像选择器上传时将图像裁剪成正方形。这在SwiftUI中是否可行/我是否漏了什么?
谢谢
我知道在使用.frame(height: 100, width: 100)
等框架修饰符的情况下,无法在大小为120和430的框架上使用.scaledToFit()
修饰符,并期望图像以某种方式保持长宽比并适合100x100的框架。
所以,似乎唯一的解决方法是强制用户在使用图像选择器上传时将图像裁剪成正方形。这在SwiftUI中是否可行/我是否漏了什么?
谢谢
aspectRatio(contentMode:)
:Image("imageName")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100, height: 100)
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
}
}