Skip to content

A SwiftUI View to display SVGs using WKWebView

License

Notifications You must be signed in to change notification settings

ZeeZide/SVGWebView

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SVGWebView

SwiftUI Swift5.3 macOS iOS Build and Test

A SwiftUI View to display SVGs (Scalable Vector Graphics) using a WKWebView.

Example usage in SVG Shaper for SwiftUI (it is the View displaying the SVG in the upper left): SVG Shaper Screenshot

Note: SVG Shaper is for converting SVGs to SwiftUI source code (which then gets compiled). SVGWebView is for displaying SVG resources (e.g. loaded from a bundle or the web) at runtime. They serve different purposes.

Usage

This is just a single file, the SVGWebView.swift is small enough for just copying it to your project. But it can also be embedded as a SwiftPM package.

IMPORTANT: On macOS WKWebView requires the "Outgoing Connections" (client) entitlement to operate, w/o it'll show up blank. iOS doesn't seem to require anything extra.

With iOS Xcode Previews do not work quite right, best to test in a real simulator.

Adding the Package

The package URL is: https://github.com/ZeeZide/SVGWebView.git

Using it in a SwiftUI App

Simply pass the SVG string to the View. For example:

import SwiftUI
import SVGWebView

struct ContentView: View {

    var body: some View {
        SVGWebView(svg:
            """
            <svg xmlns="http://www.w3.org/2000/svg"
                 viewBox="0 0 100 100">
              <rect x="10" y="10"
                    width="80" height="80"
                    fill="gold" stroke="blue"
                    stroke-width="4" />
            </svg>
            """
        )
        .frame(width: 300, height: 200)
    }
}

struct ContentView_Previews: PreviewProvider {

    static var previews: some View {
        ContentView()
    }
}

Who

SVGWebView is brought to you by ZeeZide. We like feedback, GitHub stars, cool contract work, presumably any form of praise you can think of.