我对你提供的两个矢量图像进行了并排比较:
起初,我使用了SwiftUI
内置的Image
,但正如之前提到的,两者在极端情况下表现不佳:
- 当缩小大图像时,边缘变得锐利
- 当放大小图像时,变得模糊
起初我以为可能是你的pdf矢量图像有问题,所以我使用了我之前项目中表现良好的矢量图像,但问题依旧。
认为这可能是UIImage
的问题,我使用了SwiftUI
的Image(uiImage:)
,但问题仍然存在。
最后一个猜测是图像容器,知道UIImageView
可以很好地处理矢量图像,于是使用UIViewRepresentable
来包装UIImageView
似乎解决了这个问题。目前看来,这是一个可能的解决方法。
解决方法:
struct MyImageView: UIViewRepresentable {
var name: String
var contentMode: UIView.ContentMode = .scaleAspectFit
var tintColor: UIColor = .black
func makeUIView(context: Context) -> UIImageView {
let imageView = UIImageView()
imageView.setContentCompressionResistancePriority(.fittingSizeLevel,
for: .vertical)
return imageView
}
func updateUIView(_ uiView: UIImageView, context: Context) {
uiView.contentMode = contentMode
uiView.tintColor = tintColor
if let image = UIImage(named: name) {
uiView.image = image
}
}
}
这将丢失一些 SwiftUI
的Image
修饰符(您仍然拥有普通的View
修饰符),但是您总可以像上面展示的那样传入一些参数,例如contentMode
和tintColor
。如果需要,可以添加更多并进行相应处理。
用法示例:
struct ContentView: View {
var body: some View {
VStack {
MyImageView(name: "icon",
contentMode: .scaleAspectFit,
tintColor: .black )
.frame(width: 27, height: 27)
MyImageView(name: "icon_small",
contentMode: .scaleAspectFit,
tintColor: .black )
.frame(width: 27, height: 27)
}
}
}
现在这只是猜测,但看起来 SwiftUI
把矢量图像当作一个 PNG
处理。
下面的例子是一个简单的左右对比,展示了在 UIKit
的 UIImageView
和 SwiftUI
的 Image
中渲染的小和大矢量图像。
对比:
struct ContentView: View {
let (largeImage, smallImage) = ("icon", "icon_small")
let range = stride(from: 20, to: 320, by: 40).map { CGFloat($0) }
var body: some View {
List(range, id: \.self) { (side) in
ScrollView(.horizontal) {
VStack(alignment: .leading) {
Text(String(format: "%gx%g", side, side))
HStack {
VStack {
Text("UIKit")
MyImageView(name: self.smallImage)
.frame(width: side, height: side)
MyImageView(name: self.largeImage)
.frame(width: side, height: side)
}
VStack {
Text("SwiftUI")
Image(self.smallImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: side)
Image(self.largeImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: side)
}
}
}
}
}
}
}
结果:
- 上排左边:在
UIImageView
中显示小图像
- 上排右边:在
SwiftUI
Image
中显示小图像
- 下排左边:在
UIImageView
中显示大图像
- 下排右边:在
SwiftUI
Image
中显示大图像
UIKit
的UIImageView
表现一致,而SwiftUI
的Image
存在问题。
![20x20](https://istack.dev59.com/Phs8f.webp)
![60x60](https://istack.dev59.com/23Jf8.webp)
![100x100](https://istack.dev59.com/Zbp3N.webp)
![180x180](https://istack.dev59.com/5GnA8.webp)
icon.pdf
和icon_small.pdf
?我的第一猜测是icon.pdf
出了问题。直接使用icon_small.pdf
适用于所有尺寸。它是矢量图像,会根据需要进行缩放。 - staticVoidManSwiftUI
中矢量图像支持的问题。让我们看看其他人有什么说法。 - staticVoidMan