wake-ios/wake/Utils/SVGImage.swift
2025-09-02 20:29:25 +08:00

92 lines
2.7 KiB
Swift

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 = """
<!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;
}
.container {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
svg {
\(svgStyle)
display: block;
}
</style>
</head>
<body>
<div class="container">
<object type="image/svg+xml" data="\(fileURL.lastPathComponent)"></object>
</div>
</body>
</html>
"""
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()
}