How to display .svg image using swift

前端 未结 13 878
你的背包
你的背包 2020-11-30 00:37

I have a .svg image file I want to display in my project.

I tried using UIImageView, which works for the .png & .jpg image formats, but not for the .svg extensi

13条回答
  •  执笔经年
    2020-11-30 00:46

    Here's a simple class that can display SVG images in a UIView

    import UIKit
    
    public class SVGImageView: UIView {
        private let webView = UIWebView()
    
        public init() {
            super.init(frame: .zero)
            webView.delegate = self
            webView.scrollView.isScrollEnabled = false
            webView.contentMode = .scaleAspectFit
            webView.backgroundColor = .clear
            addSubview(webView)
            webView.snp.makeConstraints { make in
                make.edges.equalTo(self)
            }
        }
    
        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
        deinit {
            webView.stopLoading()
        }
    
        public func load(url: String) {
            webView.stopLoading()
            if let url = URL(string: fullUrl) {
                webView.loadRequest(URLRequest(url: url))
            }
        }
    }
    
    extension SVGImageView: UIWebViewDelegate {
        public func webViewDidFinishLoad(_ webView: UIWebView) {
            let scaleFactor = webView.bounds.size.width / webView.scrollView.contentSize.width
            if scaleFactor <= 0 {
                return
            }
    
            webView.scrollView.minimumZoomScale = scaleFactor
            webView.scrollView.maximumZoomScale = scaleFactor
            webView.scrollView.zoomScale = scaleFactor
        }
    }
    

提交回复
热议问题