wake-ios/wake/Views/Utils/SVGImage.swift
2025-08-21 19:40:20 +08:00

68 lines
2.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import SwiftUI
import WebKit
struct SVGImage: UIViewRepresentable {
let svgName: String
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
webView.isOpaque = false
webView.backgroundColor = .clear
webView.scrollView.isScrollEnabled = false
webView.scrollView.contentInsetAdjustmentBehavior = .never
// 1. SVG inDirectory
guard let path = Bundle.main.path(forResource: svgName, ofType: "svg") else {
print("❌ 无法找到 SVG 文件: \(svgName).svg")
//
if let resourcePath = Bundle.main.resourcePath {
print("可用的资源文件: \(try? FileManager.default.contentsOfDirectory(atPath: resourcePath))")
}
return webView
}
// 2. URL
let fileURL = URL(fileURLWithPath: path)
// 3. HTML
let htmlString = """
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: transparent;
}
svg {
width: 100%;
height: 100%;
display: block;
}
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<div style="width:100%; height:100%; display:flex; align-items:center; justify-content:center;">
<img src="\(fileURL.lastPathComponent)" />
</div>
</body>
</html>
"""
// 4. HTML
webView.loadHTMLString(htmlString, baseURL: fileURL.deletingLastPathComponent())
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
}