来自 JSON 的 Xcode 12 和 SVG 快速

问题描述

我需要将从 JSON 加载的 SVG 图像显示图像视图中,但我有两个问题:

  1. JSON 数据包含一个参数 BODY,其 SVG 代码为字符串或空

模型

  struct ResultItem: Codable{
       let id:   Int
       let players: [ResultPlayer]
       let body: String? //<------- Now it was fixed!
     }
  1. 如何使用图像中的SVG字符串?我不想使用任何外部库 but Xcode12 SVG

我想使用 SVG 来替换我当前的代码

let storyboard = UIStoryboard(name: "Main",bundle: nil)
guard let vc = storyboard.instantiateViewController(withIdentifier: "Detail") as? DetailViewController else { return }        
vc.selectedImage = "logo_2-mini.png"
self.present(vc,animated: true)

你能帮我用一个字符串作为 SVG 图像吗?

let svg = "<svg width=\"100\" height=\"100\"><circle cx=\"50\" cy=\"50\" r=\"40\" stroke=\"green\" stroke-width=\"4\" fill=\"yellow\" /></svg>”.

解决方法

您需要的是 UIImage 中的 SVG 支持,但不幸的是,我们没有。 Xcode 12 带来的变化是在资产目录中支持 SVG,但是当您只在运行时获取 SVG 数据时,这无济于事。

根据您的具体问题,您或许可以使用 WKWebView 来渲染 SVG,请参见例如How to display .svg image using swift 了解更多详情。

否则,您将不得不求助于 SVGKit 等 3rd 方库。