Search code examples
svgswiftuiuiviewrepresentable

How could I use PocketSVG to display the entire SVG image in the SwiftUI?


My source code is very simple as follow:

//
//  SVGImage.swift
//  WorldRoad
//
//  Created by norains on 2019/11/26.
//  Copyright © 2019 norains. All rights reserved.
//

import PocketSVG
import SwiftUI

struct SVGImage: UIViewRepresentable {

    func makeUIView(context: Context) -> SVGImageView {
        let url = Bundle.main.url(forResource: "tiger", withExtension: "svg")!
        let svgImageView = SVGImageView.init(contentsOf: url)
        //svgImageView.frame = view.bounds //Could not set the frame here
        svgImageView.contentMode = .scaleAspectFit
        
        return svgImageView
    }

    func updateUIView(_ view: SVGImageView, context: Context) {
        
    }
}

struct SVGImage_Previews: PreviewProvider {
    static var previews: some View {
        return SVGImage()
    }
}

But it display just like that: enter image description here

It looks like the view is bigger than the screen.

The normal should like this: enter image description here

How could I do ? Thank you!


Solution

  • It will work if you embed the SVGImageView inside a UIView like the following:

    import PocketSVG
    import SwiftUI
    
    struct SVGImage: UIViewRepresentable {
        func makeUIView(context: Context) -> UIView {
            let svgView = UIView(frame: UIScreen.main.bounds)
            let url = Bundle.main.url(forResource: "tiger", withExtension: "svg")!
            let svgImageView = SVGImageView.init(contentsOf: url)
            svgImageView.frame = svgView.bounds
            svgImageView.contentMode = .scaleAspectFit
            svgView.addSubview(svgImageView)
    
            return svgView
        }
    
        func updateUIView(_ view: UIView, context: Context) {
    
        }
    }
    
    struct SVGImage_Previews: PreviewProvider {
        static var previews: some View {
            return SVGImage()
        }
    }