如何使用PocketSVG在SwiftUI中显示整个SVG图像?

时间:2019-11-26 23:26:45

标签: svg swiftui uiviewrepresentable

我的源代码非常简单,如下所示:

//
//  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()
    }
}

但是它显示如下: enter image description here

看起来比屏幕大。

正常人应该这样: enter image description here

我该怎么办?谢谢!

1 个答案:

答案 0 :(得分:0)

如果您将SVGImageView嵌入UIView内,如下所示:

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()
    }
}