SVG檔案是向量圖示準之一,特點是可以縮放,並且可以用可以閱讀的原始碼的方式(而不是二進位制)來儲存圖形資訊。比如如下檔案就是一個svg檔案:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 350 100">
<defs>
<marker id="arrowhead" markerWidth="10" markerHeight="7"
refX="0" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" />
</marker>
</defs>
<line x1="0" y1="50" x2="250" y2="50" stroke="#000"
stroke-width="8" marker-end="url(#arrowhead)" />
</svg>複製程式碼
它是一個箭頭圖。可以使用UIWebView檢視載入此檔案並顯示。首先把SVG檔案作為資原始檔加入工程,命名為1.svg。
其實,使用如下程式碼載入此檔案:
var path: String = Bundle.main.path(forResource: "1", ofType: "svg")!
var url: NSURL = NSURL.fileURL(withPath: path) as NSURL
var request: NSURLRequest = NSURLRequest(url: url as URL)
webview?.loadRequest(request as URLRequest)複製程式碼
完整程式碼如下:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
let page = Page()
page.view.backgroundColor = .blue
self.window!.rootViewController = page
self.window?.makeKeyAndVisible()
return true
}
}
class Page: UIViewController {
var count = 0
var webview : UIWebView!
var webview1 : UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webview = UIWebView()
webview?.frame = CGRect(x: 0, y: 100, width: 100, height: 100)
view.addSubview(webview!)
webview1 = UIWebView()
webview1.frame = CGRect(x: 0, y: 200, width: 50, height: 50)
view.addSubview(webview1!)
let path: String = Bundle.main.path(forResource: "1", ofType: "svg")!
let url: NSURL = NSURL.fileURL(withPath: path) as NSURL
let request: NSURLRequest = NSURLRequest(url: url as URL)
webview?.loadRequest(request as URLRequest)
webview1.loadRequest(request as URLRequest)
}
}複製程式碼
本意是想用它來替換點陣圖圖示,但是看起來載入速度堪憂。