import SwiftUI import WebKit struct SVGImage: UIViewRepresentable { let svgName: String var shouldFill: Bool = false func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() webView.isOpaque = false webView.backgroundColor = .clear webView.scrollView.isScrollEnabled = false webView.scrollView.contentInsetAdjustmentBehavior = .never guard let path = Bundle.main.path(forResource: svgName, ofType: "svg") else { print("❌ 无法找到 SVG 文件: \(svgName).svg") return webView } let fileURL = URL(fileURLWithPath: path) let svgStyle = shouldFill ? """ width: 100%; height: 100%; object-fit: cover; """ : """ max-width: 100%; max-height: 100%; object-fit: contain; """ let htmlString = """
""" webView.loadHTMLString(htmlString, baseURL: fileURL.deletingLastPathComponent()) return webView } func updateUIView(_ uiView: WKWebView, context: Context) {} func sizeThatFits(_ proposal: ProposedViewSize, uiView: WKWebView, context: Context) -> CGSize? { return nil } } // MARK: - Preview #Preview { VStack { Text("Filled SVG") SVGImage(svgName: "YourSVGName", shouldFill: true) .frame(width: 200, height: 100) .background(Color.gray.opacity(0.2)) Text("Intrinsic Size SVG") SVGImage(svgName: "YourSVGName", shouldFill: false) .frame(width: 200, height: 100) .background(Color.gray.opacity(0.2)) } .padding() }