Skip to content

SVGView resizing

Yuri Strot edited this page May 15, 2022 · 1 revision

By default SVGView fills all available space the same way as Color or Rectangle views do.

struct ContentView: View {

    let content = """
        <svg viewBox="0 0 10 10">
            <circle cx="5" cy="5" r="5" fill="blue"/>
        </svg>
    """

    var body: some View {
        SVGView(string: content)
    }

}

Every SVG file has build-in aspect ration attribute, which is by default equals to aspect fit. If you would like to change aspect ration, you need to change it in your SVG file. For example, use "xMidYMid slice" value to aspect fill.

struct ContentView: View {

    let content = """
        <svg viewBox="0 0 10 10" preserveAspectRatio="xMidYMid slice">
            <circle cx="5" cy="5" r="5" fill="blue"/>
        </svg>
    """

    var body: some View {
        SVGView(string: content)
    }

}

If you'd like to specify a fixed size for your SVG art you need to use frame method:

struct ContentView: View {

    let content = """
        <svg viewBox="0 0 10 10">
            <circle cx="5" cy="5" r="5" fill="blue"/>
        </svg>
    """

    var body: some View {
        SVGView(string: content)
            .frame(width: 100, height: 100)
    }

}

Some SVG files can have default size by specifying width/height attributes. If you want to use this default size, just call fixedSize method on SVGView:

struct ContentView: View {

    let content = """
        <svg width="200" height="200" viewBox="0 0 10 10">
            <circle cx="5" cy="5" r="5" fill="blue"/>
        </svg>
    """

    var body: some View {
        SVGView(string: content)
            .fixedSize()
    }

}
Clone this wiki locally