ios 如何使用 swift 显示 .svg 图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35691839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:37:30  来源:igfitidea点击:

How to display .svg image using swift

iosswiftuiwebview

提问by Priyanka Kanse

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

我有一个要在我的项目中显示的 .svg 图像文件。

I tried using UIImageView, which works for the .png & .jpg image formats, but not for the .svg extension. Is there any way to display a .svg image using UIWebView or UIImageView ?

我尝试使用 UIImageView,它适用于 .png 和 .jpg 图像格式,但不适用于 .svg 扩展名。有没有办法使用 UIWebView 或 UIImageView 显示 .svg 图像?

采纳答案by Komal Kamble

Try this code

试试这个代码

var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!

        var url: NSURL = NSURL.fileURLWithPath(path)  //Creating a URL which points towards our path

       //Creating a page request which will load our URL (Which points to our path)
        var request: NSURLRequest = NSURLRequest(URL: url)
       webView.loadRequest(request)  //Telling our webView to load our above request

回答by Sujay U N

There is no Inbuilt support for SVG in Swift. So we need to use other libraries.

Swift 中没有对 SVG 的内置支持。所以我们需要使用其他库。

The simple SVG libraries in swift are :

swift 中的简单 SVG 库是:

1) SwiftSVGLibrary

1) SwiftSVG

It gives you more option to Import as UIView, CAShapeLayer, Path, etc

它为您提供了更多选项以导入为 UIView、CAShapeLayer、Path 等

To modify your SVG Color and Import as UIImage you can use my extension codes for the library mentioned in below link,

要修改您的 SVG 颜色并导入为 UIImage,您可以将我的扩展代码用于以下链接中提到的库,

Click here to know on using SwiftSVGlibrary :
Using SwiftSVG to set SVG for Image

单击此处了解使用SwiftSVG库:
使用 SwiftSVG 为图像设置 SVG

|OR|

|或|

2) SVGKitLibrary

2) SVGKit

2.1) Use pod to install :

2.1)使用pod安装:

pod 'SVGKit', :git => 'https://github.com/SVGKit/SVGKit.git', :branch => '2.x'

2.2) Add framework

2.2) 添加框架

Goto AppSettings
-> General Tab
-> Scroll down to Linked Frameworks and Libraries
-> Click on plus icon
-> Select SVG.framework

转到 AppSettings
-> General Tab
-> 向下滚动到 Linked Frameworks and Libraries
-> 单击加号图标
-> 选择 SVG.framework

2.3) Add in Objective-C to Swift bridge file bridging-header.h :

2.3) 将 Objective-C 添加到 Swift 桥文件 bridging-header.h :

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

2.4) Create SvgImg Folder (for better organization) in Project and add SVG files inside it.

2.4) 在项目中创建 SvgImg 文件夹(为了更好的组织)并在其中添加 SVG 文件。

Note : Adding Inside Assets Folder won't work and SVGKit searches for file only in Project folders

注意:添加内部资产文件夹不起作用,SVGKit 仅在项目文件夹中搜索文件

2.5) Use in your Swift Code as below :

2.5) 在您的 Swift 代码中使用如下:

import SVGKit

and

let namSvgImgVar: SVGKImage = SVGKImage(named: "NamSvgImj")

Note : SVGKit Automatically apends extention ".svg" to the string you specify

注意:SVGKit 自动将扩展名“.svg”附加到您指定的字符串

let namSvgImgVyuVar = SVGKImageView(SVGKImage: namSvgImgVar)

let namImjVar: UIImage = namSvgImgVar.UIImage

There are many more options for you to init SVGKImage and SVGKImageView

有更多选项供您初始化 SVGKImage 和 SVGKImageView

There are also other classes u can explore

您还可以探索其他课程

    SVGRect
    SVGCurve
    SVGPoint
    SVGAngle
    SVGColor
    SVGLength

    and etc ...

回答by Vitalii

You can use SVGKitfor example.

例如,您可以使用SVGKit

1) Integrate it according to instructions. Drag&dropping the .framework file is fast and easy.

1) 按照说明进行集成。拖放 .framework 文件既快速又简单。

2) Make sure you have an Objective-C to Swift bridge file bridging-header.h with import code in it:

2) 确保你有一个 Objective-C 到 Swift 的桥文件 bridging-header.h ,其中包含导入代码:

#import <SVGKit/SVGKit.h>
#import <SVGKit/SVGKImage.h>

3) Use the framework like this, assuming that dataFromInternet is NSData, previously downloaded from network:

3)使用这样的框架,假设dataFromInternet是NSData,之前是从网络下载的:

let anSVGImage: SVGKImage = SVGKImage(data: dataFromInternet)
myIUImageView.image = anSVGImage.UIImage

The framework also allows to init an SVGKImage from other different sources, for example it can download image for you when you provide it with URL. But in my case it was crashing in case of unreachable url, so it turned out to be better to manage networking by myself. More info on it here.

该框架还允许从其他不同来源初始化 SVGKImage,例如,当您提供 URL 时,它可以为您下载图像。但在我的情况下,它在无法访问的 url 的情况下崩溃,所以结果证明自己管理网络会更好。关于它的更多信息在这里

回答by Paresh Navadiya

Swift 3.0 version :

斯威夫特 3.0 版本:

let path = Bundle.main.path(forResource: "svgNameFileHere", ofType: "svg")!
if path != "" {
    let fileURL:URL = URL(fileURLWithPath: path)
    let req = URLRequest(url: fileURL)
    self.webView.scalesPageToFit = false
    self.webView.loadRequest(req)
}
else {
   //handle here if path not found
}

Third party libraries

第三方库

https://github.com/exyte/Macaw

https://github.com/exyte/Macaw

https://github.com/mchoe/SwiftSVG

https://github.com/mchoe/SwiftSVG

UIWebView and WKWebView booster to load faster

UIWebView 和 WKWebView 助推器加载速度更快

https://github.com/bernikovich/WebViewWarmUper

https://github.com/bernikovich/WebViewWarmUper

回答by GabrielaBezerra

In case you want to use a WKWebViewto load a .svg image that is coming from a URLRequest, you can simply achieve it like this:

如果您想使用 aWKWebView加载来自 a 的 .svg 图像URLRequest,您可以像这样简单地实现它:

Swift 4

斯威夫特 4

if let request = URLRequest(url: urlString), let svgString = try? String(contentsOf: request) {
  wkWebView.loadHTMLString(svgString, baseURL: request)
}

It's much simpler than the other ways of doing it, and you can also persist your .svg string somewhere to load it later, even offline if you need to.

它比其他方法简单得多,您还可以将 .svg 字符串保存在某处以便稍后加载,如果需要,甚至可以离线加载。

回答by nikhilgohil11

You can add New Symbol Image Setin .xcassets, then you can add SVG file in it

您可以在 .xcassets 中添加New Symbol Image Set,然后您可以在其中添加 SVG 文件

and use it same like image.

并像图像一样使用它。

enter image description here

在此处输入图片说明

Note: This doesn't work on all SVG. You can have a look at the apple documentation

注意:这不适用于所有 SVG。你可以看看苹果文档

回答by nanvel

You can keep your images as strings and use WKWebView to display them:

您可以将图像保留为字符串并使用 WKWebView 来显示它们:

let webView: WKWebView = {
    let mySVGImage = "<svg height=\"190\"><polygon points=\"100,10 40,180 190,60 10,60 160,180\" style=\"fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;\"></svg>"
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = false
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    let wv = WKWebView(frame: .zero, configuration: configuration)
    wv.scrollView.isScrollEnabled = false
    wv.loadHTMLString(mySVGImage, baseURL: nil)
    return wv
}()

回答by wes

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

这是一个简单的类,可以在一个 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
    }
}

回答by Vlad Bruno

My solution to show .svg in UIImageView from URL. You need to install SVGKitpod

我从 URL 在 UIImageView 中显示 .svg 的解决方案。你需要安装SVGKitpod

Then just use it like this:

然后像这样使用它:

import SVGKit

 let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
 let data = try? Data(contentsOf: svg)
 let receivedimage: SVGKImage = SVGKImage(data: data)
 imageview.image = receivedicon.uiImage

or you can use extension for async download

或者您可以使用扩展程序进行异步下载

extension UIImageView {
func downloadedsvg(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let receivedicon: SVGKImage = SVGKImage(data: data),
            let image = receivedicon.uiImage
            else { return }
        DispatchQueue.main.async() {
            self.image = image
        }
    }.resume()
}
}

How to use:

如何使用:

let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!

imageview.downloadedsvg(from: svg)

回答by Iurie

As I know there are 2 different graphic formats:

据我所知,有两种不同的图形格式:

  1. Raster graphics (uses bitmaps) and is used in JPEG, PNG, APNG, GIF, and MPEG4 file format.
  2. Vector graphics (uses points, lines, curves and other shapes). Vector graphics are used in the SVG, EPS, PDF or AI graphic file formats.
  1. 光栅图形(使用位图),用于 JPEG、PNG、APNG、GIF 和 MPEG4 文件格式。
  2. 矢量图形(使用点、线、曲线和其他形状)。矢量图形用于 SVG、EPS、PDF 或 AI 图形文件格式。

So if you need to use an image stored in SVG File in your Xcode I would suggest:

因此,如果您需要在 Xcode 中使用存储在 SVG 文件中的图像,我建议:

  1. Convert SVG file to PDF. I used https://document.online-convert.com/convert/svg-to-pdf

  2. Use Xcode to manage you PDF file.

  1. 将 SVG 文件转换为 PDF。我使用了 https://document.online-convert.com/convert/svg-to-pdf

  2. 使用 Xcode 来管理您的 PDF 文件。